python psycopg2未插入PostgreSQL表 [英] Python psycopg2 not inserting into postgresql table

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

问题描述

我正在使用以下方法尝试将记录插入到postgresql数据库表中,但是它不起作用。我没有任何错误,但表中没有记录。我需要提交或其他东西吗?我正在使用随Bitnami djangostack安装安装的postgresql数据库。

I'm using the following to try and insert a record into a postgresql database table, but it's not working. I don't get any errors, but there are no records in the table. Do I need a commit or something? I'm using the postgresql database that was installed with the Bitnami djangostack install.

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"


推荐答案

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

If don't want to have to commit each entry to the database, you can add the following line:

conn.autocommit = True

因此,您得到的代码将是:

So your resulting code would be:

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"

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

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