Python psycopg2 未能插入到postgresql表

2024-09-28 22:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下命令尝试将记录插入到postgresql数据库表中,但它不起作用。我没有任何错误,但表中没有记录。我需要承诺什么的吗?我使用的是与Bitnami djangostack安装一起安装的postgresql数据库。

import psycopg2

try:
    conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'")
except:
    print "Cannot connect to db"

cur = conn.cursor()

try:
    cur.execute("""insert into cnet values ('r', 's', 'e', 'c', 'w', 's', 'i', 'd', 't')""")
except:
    print "Cannot insert"

Tags: 命令数据库postgresqlconnect记录passwordconnpsycopg2
3条回答

结果我最后需要conn.commit()

psycopg2Python DB API兼容,因此自动提交功能在默认情况下处于关闭状态。您需要调用^{}将任何挂起的事务提交到数据库。由于连接(和游标)是上下文管理器,您只需使用with语句在离开上下文时自动提交/回滚事务:

with conn, conn.cursor() as cur:  # start a transaction and create a cursor
    cur.execute(sql)

docs

When a connection exits the with block, if no exception has been raised by the block, the transaction is committed. In case of exception the transaction is rolled back.

When a cursor exits the with block it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected.

如果不想将每个条目提交到数据库,可以添加以下行:

conn.autocommit = True

所以你得到的代码是:

import psycopg2

try:
    conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'")
    conn.autocommit = True
except:
    print "Cannot connect to db"

cur = conn.cursor()

try:
    cur.execute("""insert into cnet values ('r', 's', 'e', 'c', 'w', 's', 'i', 'd', 't')""")
except:
    print "Cannot insert"

相关问题 更多 >