如何使用Python在 PostgreSQL 中定义自动递增主键?
先决条件:PostgreSQL
Python有各种用于 PostgreSQL 的数据库驱动程序。目前,最常用的版本是 psycopg2,因为它完全实现了Python DB-API 2.0 规范。 psycopg2 提供了许多有用的功能,例如客户端和服务器端游标、异步通知和通信、COPY 命令支持等。
安装
可以使用以下命令像任何其他模块一样下载 psycopg2:
pip install psycopg2
方法
PostgreSQL 使用自增功能创建主键的方法:
必须使用SERIAL PRIMARY KEY 定义列。这里 SERIAL 不是真正的数据类型,而只是简单的速记符号,它告诉 Postgres 为指定的列创建一个自动递增的唯一标识符。通过简单地将列设置为带有 PRIMARY KEY 的 SERIAL,Postgres 将处理所有复杂的幕后工作,并为每个 INSERT 自动增加具有唯一主键值的指定列。
数据库信息
数据库名称: testdb
表名: EMPLOYEE
在 EMPLOYEE TABLE 中,名为 EMPLOYEE_ID 的列将实现为自动递增的主键列。
句法:
CREATE TABLE
.
.
);
创建具有此类规范的表的实现如下:
Python3
import psycopg2
def create_table():
conn = None
try:
# connect to the PostgreSQL server
conn = psycopg2.connect(database="testdb", user="postgres",
password="password", host="127.0.0.1", port="5432")
print("Opened database successfully")
# create a cursor
cursor = conn.cursor()
# Droping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Creating table as per requirement, let us have EMPLOYEE table
# and in order to have auto increment primary key, EMPLOYEE_ID SERIAL PRIMARY KEY
# is used and it is explained before code
sql = '''CREATE TABLE EMPLOYEE(
EMPLOYEE_ID SERIAL PRIMARY KEY,
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
)'''
cursor.execute(sql)
print("Table created successfully........")
# close communication with the PostgreSQL database server
cursor.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
create_table()
Python3
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="password",
host="127.0.0.1",
port="5432",
database="testdb")
cursor = connection.cursor()
# As Employee table is having auto incremented primary id column(employee_id), no need to specify about that value here
postgres_insert_query = ''' INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE,SEX,INCOME) VALUES (%s,%s,%s,%s,%s)'''
record_to_insert = ('asd', 'wer', 19, 'f', 5000)
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into Employee table")
except (Exception, psycopg2.Error) as error:
if(connection):
print("Failed to insert record into Employee table", error)
finally:
# closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
我们可以看到使用 pgadmin 工具创建的表
现在,需要完成插入以查看我们的自动增量功能是否有效。这可以直接通过 pgadmin 或使用Python代码完成。
pgadmin 方式:
下面是显示插入查询和结果集的执行的屏幕截图。
使用Python代码:
蟒蛇3
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="password",
host="127.0.0.1",
port="5432",
database="testdb")
cursor = connection.cursor()
# As Employee table is having auto incremented primary id column(employee_id), no need to specify about that value here
postgres_insert_query = ''' INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE,SEX,INCOME) VALUES (%s,%s,%s,%s,%s)'''
record_to_insert = ('asd', 'wer', 19, 'f', 5000)
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into Employee table")
except (Exception, psycopg2.Error) as error:
if(connection):
print("Failed to insert record into Employee table", error)
finally:
# closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
执行上述程序后员工表的输出: