Python psycopg2 实际上没有插入数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13715743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:27:16  来源:igfitidea点击:

psycopg2 not actually inserting data

pythonpostgresqlpsycopg2

提问by juk

I need to insert JSON data from tornado to postgres, so here's test like this:

我需要将 JSON 数据从 tornado 插入到 postgres,所以这里的测试是这样的:

from psycopg2 import connect

conn = connect("user='pguser' host='localhost' dbname='pgdb' password='pgpass'")
cursor = conn.cursor()

data = '[{"id":"sdf","name":"wqe","author":"vb"}]'

for row in eval(data):
  print row
  cursor.execute("""INSERT INTO books(id,name,author) VALUES('%s','%s','%s')""" % \
        (row['id'], row['name'], row['author'])
  )

>>> cursor.execute("SELECT * FROM books")
>>> cursor.fetchall()
[('sdf', 'wqe', 'vb')]
>>> 
$> psql -d pgdb -U pguser -W
Password for user pguser: 
psql (9.1.6)
Type "help" for help.

pgdb=> select * from books;
 id | name | author 
----+------+--------
(0 rows)

As you can see after doing selectin python shell, there's some data, but in psql there's 0 rows! What may I be doing wrong?

正如你select在 python shell 中所做的那样,有一些数据,但在 psql 中有 0 行!我可能做错了什么?

Python 2.7.2+

蟒蛇 2.7.2+

采纳答案by Craig Ringer

You didn't commit the transaction.

你没有提交交易。

Psycopg2 opens a transaction automatically, and you must tell it to commit in order to make the data visible to other sessions.

Psycopg2 自动打开一个事务,您必须告诉它提交以使数据对其他会话可见。

See the psycopg2 FAQand the connection.commit()method.

请参阅psycopg2 FAQconnection.commit()方法