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

发布于 2024-07-04 01:22:21 字数 794 浏览 7 评论 0原文

有没有办法让 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

Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with 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

This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

计㈡愣 2024-07-11 01:22:21

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

First of all you should let psycopg do the escaping for you by passing to the execute() method the parameters instead of doing the formatting yourself with '%'. That is:

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

Note how we use "%s" as a marker even for non-string values and avoid quotes in the query. psycopg will do all the quoting for us.

Then, if you want to ignore some errors, just rollback and continue.

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

That's all. psycopg will rollback and start a new transaction on your next statement.

怀里藏娇 2024-07-11 01:22:21

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

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() 方法,该方法专门设计用于多次执行同一语句。

I think your code looks like this at the moment:

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

So try to change it into something like this:

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

so never forget to pass your parameters in the parameters list, then you don't have to care about your quotes and stuff, it is also more secure. You can read more about it at http://www.python.org/dev/peps/pep-0249/

also have a look there at the method .executemany() which is specially designed to execute the same statement multiple times.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文