Psycopg2插入未保存 [英] Psycopg2 insert not saved

查看:84
本文介绍了Psycopg2插入未保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道的数据库副本正在监听默认端口5432,这是发生插入的地方。我应该为要连接的数据库传递自定义端口。

我需要执行的操作认为可能很重要:fetchall()返回的id与直接从psql实际插入的id不同。

Something that I think may be significant: id returned from fetchall() is different from the one actually inserted directly from psql.

我执行的脚本:

import os
import psycopg2

conn_config = {
    'host': os.environ['DB_HOST'],
    'dbname': os.environ['DB_NAME'],
    'user': os.environ['DB_USER'],
    'password': os.environ['DB_PASSWD']
}
conn = psycopg2.connect(**conn_config)
cur = conn.cursor()
sql = """INSERT INTO file(file_title, file_descrip) VALUES ('test','giannis') RETURNING file_id;"""
cur.execute(sql)
print(cur.fetchall())
conn.commit()
cur.close()
conn.close()

输出:

>>>[(76,)]

使用相同的凭据从与数据库相同的机器:

Connecting with the same credentials, from the same machine to the DB:

select * from file where file.file_id=76;
 file_id | file_title | file_stream | file_descrip | obj_uuid
---------+------------+-------------+--------------+----------
(0 rows)

然后从psql的同一会话中,复制上面的SQL语句:

And from the same session within psql, copying the above SQL statement:

INSERT INTO file(file_title, file_descrip) VALUES ('test','giannis') RETURNING file_id;
 file_id
---------
      57
(1 row)

INSERT 0 1
my_db=> select * from file where file.file_id=57;
-[ RECORD 1 ]+-------------------------------------
file_id      | 57
file_title   | test
file_stream  |
file_descrip | giannis
obj_uuid     | 396d5d3b-efe1-422a-a6b4-d9b21381d4be


推荐答案

就像您不提交交易一样。在连接关闭之前,调用 conn.commit()

It looks like you don't commit the transaction. Call conn.commit() before the connection closes.

这篇关于Psycopg2插入未保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆