Python Psycopg错误和连接处理(v MySQLdb)
有没有办法让psycopg和postgres处理错误而不必像MySQLdb那样重新建立连接?下面的注释版本适用于MySQLdb,注释使其适用于Psycopg2:Python Psycopg错误和连接处理(v MySQLdb),python,mysql,psycopg2,Python,Mysql,Psycopg2,有没有办法让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
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,))
因此,永远不要忘记在参数列表中传递参数,这样您就不必关心您的报价和其他内容,它也更安全。你可以在
另外,请看一下方法.executemany(),它是专门为多次执行同一语句而设计的。首先,您应该让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将回滚并在下一条语句中启动一个新事务。您可以添加addthings的代码吗?因为我猜你有一个引用问题谢谢,我按照你的建议做字符串赋值。我想我更大的问题是,当我试图添加无效的东西时,我失去了连接,不得不重新建立它,我很好奇是否有办法让它更像mysqldb,在这里,可以通过正常的异常处理跳过错误