简体   繁体   English

字符串格式化程序上的python psycopg2内部错误

[英]python psycopg2 internal error on string formatter

Hi I'm trying the following script 嗨,我正在尝试以下脚本

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']))

and I get the error 我得到了错误

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

What am I doing wrong? 我究竟做错了什么?

btw the same error occurs with the line 顺便说一句,行发生相同的错误

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'))

I think you have to commit the first statement that creates the table, before you can run any inserts on it. 我认为您必须提交创建表的第一条语句,然后才能对其进行任何插入。 Try running cn.commit() in between your two SQL statements to see if that resolves the issue. 尝试在两个SQL语句之间运行cn.commit() ,以查看是否可以解决问题。

Alternatively, set autocommit=True when you create your initial connection to the database. 或者,在创建到数据库的初始连接时设置autocommit=True

Okay for completeness the tricky bit was feeding the field names in as string formatters too. 为了完整起见,还很棘手的一点是,字段名称也以字符串格式器的形式输入。

I split the code into two sections. 我将代码分为两部分。

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)

and that worked fine and (I believe) remains safe from SQL injection type attacks. 并且效果很好,并且(我相信)仍然可以免受SQL注入类型攻击的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM