1

嗨我正在尝试以下脚本

import psycopg2 as pq
import os

# Create the database
os.system('dropdb ptest')
os.system('createdb ptest')
# connect to the database
cn = pq.connect('dbname=ptest user=myname')
cr = cn.cursor()

# the wierd tuple at the EOL below is to preserve the list 
# lookup in case that is where the error is.
cr.execute('CREATE TABLE id1 (%s varchar, %s int PRIMARY KEY, %s int, %s int, %s varchar)' % tuple(['fund', 'sleeve_id', 'sub_id', 'level_id', 'Entity_id'])
cr.execute('INSERT INTO id1 (%s,%s,%s,%s,%s) VALUES ("%s","%s","%s","%s","%s");' % tuple(['fund', 'sleeve_id', 'sub_id', 'level_id', 'Entity_id']+['RHUBARB RHUBARB - RHUBARB RHUBARB', '2', '1', '1', 'CRUMB1']))

我得到了错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block

我究竟做错了什么?

顺便说一句,该行发生相同的错误

cr.execute('INSERT INTO id1 (%s,%s,%s,%s,%s) VALUES ("%s","%s","%s","%s","%s");' % ('fund', 'sleeve_id', 'sub_id', 'level_id', 'Entity_id','RHUBARB RHUBARB - RHUBARB RHUBARB', '2', '1', '1', 'CRUMB1'))
4

2 回答 2

1

我认为您必须先提交创建表的第一条语句,然后才能对其运行任何插入。尝试cn.commit()在两个 SQL 语句之间运行,看看是否能解决问题。

或者,autocommit=True在创建与数据库的初始连接时设置。

于 2013-06-14T16:54:26.093 回答
1

好的,为了完整起见,棘手的一点是将字段名称也作为字符串格式化程序输入。

我将代码分成两部分。

import psycopg2 as pq
import os

# Create the database
os.system('dropdb ptest')
os.system('createdb ptest')
# connect to the database
cn = pq.connect('dbname=ptest user=myname')
cr = cn.cursor()

# the wierd tuple at the EOL below is to preserve the list 
# lookup in case that is where the error is.
cr.execute('CREATE TABLE id1 (%s varchar, %s int PRIMARY KEY, %s int, %s int, %s varchar)' % tuple(['fund', 'sleeve_id', 'sub_id', 'level_id', 'Entity_id'])
SQL = 'INSERT INTO id1 (%s,%s,%s,%s,%s) VALUES' % tuple(['fund', 'sleeve_id', 'sub_id', 'level_id', 'Entity_id'])
SQL = SQL + ' (%s,%s,%s,%s,%s);'
data = tuple(['RHUBARB RHUBARB - RHUBARB RHUBARB', '2', '1', '1', 'CRUMB1'])
cr.execute(SQL,data)

并且效果很好并且(我相信)仍然可以免受 SQL 注入类型的攻击。

于 2013-06-17T08:01:06.233 回答