有没有办法让 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
有帮助吗?

解决方案

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

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 将回滚并在您的下一条语句中启动新事务。

其他提示

我认为你的代码现在看起来像这样:

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() 方法,它是专门为多次执行同一语句而设计的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top