我使用 psycopg2 在 Python 上连接到 PostgreSQL,我想使用连接池。
当我执行 INSERT 查询时,我不知道应该做什么来代替 commit() 和 rollback()。
db = pool.SimpleConnectionPool(1, 10,host=conf_hostname,database=conf_dbname,user=conf_dbuser,password=conf_dbpass,port=conf_dbport)
# Get Cursor
@contextmanager
def get_cursor():
con = db.getconn()
try:
yield con.cursor()
finally:
db.putconn(con)
with get_cursor() as cursor:
cursor.execute("INSERT INTO table (fields) VALUES (values) RETURNING id")
id = cursor.fetchone()
如果没有 commit(),我不会得到插入记录的 id。