簡體   English   中英

字符串格式化程序上的python psycopg2內部錯誤

[英]python psycopg2 internal error on string formatter

嗨,我正在嘗試以下腳本

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

我認為您必須提交創建表的第一條語句,然后才能對其進行任何插入。 嘗試在兩個SQL語句之間運行cn.commit() ,以查看是否可以解決問題。

或者,在創建到數據庫的初始連接時設置autocommit=True

為了完整起見,還很棘手的一點是,字段名稱也以字符串格式器的形式輸入。

我將代碼分為兩部分。

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注入類型攻擊的影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM