psycopg2相当于mysqldb.escape_string吗? [英] psycopg2 equivalent of mysqldb.escape_string?

查看:155
本文介绍了psycopg2相当于mysqldb.escape_string吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python中的psycopg2将一些值传递到postgres字符字段中。一些字符串值包含句点,斜杠,引号等。

I'm passing some values into a postgres character field using psycopg2 in Python. Some of the string values contain periods, slashes, quotes etc.

使用MySQL时,我只需使用

With MySQL I'd just escape the string with

MySQLdb.escape_string(my_string)

是否存在等同于psycopg2?

Is there an equivalent for psycopg2?

推荐答案

转义是自动的,您只需调用:

Escaping is automatic, you just have to call:

cursor.execute("query with params %s %s", ("param1", "pa'ram2"))

(请注意,未使用python%运算符),并且值将正确转义。

(notice that the python % operator is not used) and the values will be correctly escaped.

您可以使用 extensions.adapt(var)手动对变量进行转义,但这很容易出错,并且不考虑连接编码:不应在常规客户端代码中使用。

You can escape manually a variable using extensions.adapt(var), but this would be error prone and not keep into account the connection encoding: it is not supposed to be used in regular client code.

这篇关于psycopg2相当于mysqldb.escape_string吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆