[python] python postgresql gets the id of the inserted data

After using the PostgreSQL database to insert data in Python, you can use RETURNINGclauses to obtain the id of the inserted data. Here is an example:

import psycopg2

# 连接到PostgreSQL数据库
conn = psycopg2.connect(database="your_database", user="your_username", password="your_password", host="your_host", port="your_port")

# 创建一个游标对象
cur = conn.cursor()

# 执行插入数据的SQL语句,并使用RETURNING子句获取插入数据的id
cur.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s) RETURNING id", ("value1", "value2"))

# 获取插入数据的id
inserted_id = cur.fetchone()[0]
print("插入的数据id为:", inserted_id)

# 提交事务
conn.commit()

# 关闭游标和数据库连接
cur.close()
conn.close()

In the above example, we first connect to the PostgreSQL database and then create a cursor object. Next, we execute the SQL statement for inserting data, and use RETURNING idthe clause to get the id of the inserted data. Then, we use fetchone()the method to get the first row of data in the query result, that is, the id of the inserted data. Finally, we commit the transaction and close the cursor and database connection.

Note that the parameters (database name, username, password, host, and port) in the above example need to be modified according to your actual situation.

Guess you like

Origin blog.csdn.net/qq_41604569/article/details/131522249