Python Psycopg错误和连接处理(v MySQLdb)

时间:2020-03-05 18:55:29  来源:igfitidea点击:

有没有办法使psycopg和postgres处理错误而不必像MySQLdb那样重新建立连接?以下注释版本适用于MySQLdb,注释使其适用于Psycopg2:

results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....}
for item in sorted(results):
    try:
        cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item]))
        print item, results[item]
#       conn.commit()
    except:
#       conn=psycopg2.connect(user='bvm', database='wdb', password='redacted')
#       cur=conn.cursor()
        print 'choked on', item
        continue

这必须放慢速度,有人可以建议忽略格式错误吗?显然,上述情况在撇号上造成了窒息,但是有没有办法使它跳过而又不会得到以下内容,提交,重新连接等信息?

agreement 19
agreements 1
agrees 1
agrippa 9
choked on agrippa's
choked on agrippina

解决方案

回答

我认为代码目前如下所示:

l = "a very long ... text".split()
for e in l:
    cursor.execute("INSERT INTO yourtable (yourcol) VALUES ('" + e + "')")

因此,尝试将其更改为如下所示:

l = "a very long ... text".split()
for e in l:
    cursor.execute("INSERT INTO yourtable (yourcol) VALUES (%s)", (e,))

因此,永远不要忘记在参数列表中传递参数,这样就不必担心引号和内容,它也更安全。我们可以在http://www.python.org/dev/peps/pep-0249/上了解更多有关它的信息。

还可以查看.executemany()方法,该方法专门设计用于多次执行同一条语句。

回答

首先,应该通过将参数传递给execute()方法,而不是使用'%'格式化自己的格式,让psycopg为我们进行转义。那是:

cur.execute("insert into resultstab values (%s, %s)", (item, results[item]))

请注意,即使对于非字符串值,我们如何也将"%s"用作标记,并避免在查询中使用引号。 psycopg将为我们进行所有报价。

然后,如果要忽略某些错误,只需回滚并继续。

try:
    cur.execute("SELECT this is an error")
except:
    conn.rollback()

就这样。 psycopg将回滚并在下一条语句上开始新的事务。