psycopg2 实际上没有插入数据 [英] psycopg2 not actually inserting data

查看:82
本文介绍了psycopg2 实际上没有插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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 行!我可能做错了什么?

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

Python 2.7.2+

Python 2.7.2+

推荐答案

您没有提交事务.

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

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

请参阅psycopg2 常见问题解答connection.commit() 方法.

See the psycopg2 FAQ and the connection.commit() method.

这篇关于psycopg2 实际上没有插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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