我需要将龙卷风中的JSON数据插入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)
正如你在python shell中执行select
后所看到的那样,有一些数据,但在psql中有
0行!我可能做错了什么?
Python 2.7.2 +
答案 0 :(得分:136)
答案 1 :(得分:0)
遇到同样的困惑问题。将选项放在一起:
正如@Craig Ringer在cursor.execute之后写的那样,您可以运行connection.commit
cursor.execute('INSERT INTO table VALUES(DEFAULT, %s)', email)
...
connection.commit()
或 连接后设置自动提交
connection = connect("user='pguser' host='localhost' dbname='pgdb' password='pgpass'")
connection.autocommit = True
或 使用set_session设置自动提交
connection = connect("user='pguser' host='localhost' dbname='pgdb' password='pgpass'")
connection.set_session(autocommit=True)
所有人都为我工作。