【问题标题】:psycopg2 vs MySQLdb backslash escaping behaviourpsycopg2 vs MySQLdb 反斜杠转义行为
【发布时间】:2020-12-24 21:12:51
【问题描述】:
import MySQLdb
import psycopg2

# CREATE DATABASE mytest CHARACTER SET utf8;
db=MySQLdb.connect(host="localhost",user="anton",
        passwd="password",db="mytest")

cur = db.cursor()
cur.execute("drop table if exists mytable")
cur.execute("create table mytable (textcol text)")
cur.execute("insert into mytable values (' some \\\\ escaped stuff')")
cur.execute("select * from mytable")
print(cur.fetchall())


# CREATE DATABASE mytest ENCODING 'UTF8';
db=psycopg2.connect(host="localhost",user="anton",
        password="password",dbname="mytest")

cur = db.cursor()

cur.execute("drop table if exists mytable")
cur.execute("create table mytable (textcol text)")
cur.execute("insert into mytable values (' some \\\\ escaped stuff')")
cur.execute("select * from mytable")

print(cur.fetchall())

哪些输出:

((' some \\ escaped stuff',),)
[(' some \\\\ escaped stuff',)]

基本上,我想要的是能够使用相同的插入 sql(我无法修改)并能够通过添加一些参数来使用两个 db 驱动程序为 text 列返回相同的内容连接。我都找不到如何控制这种行为,所以卡住了。

【问题讨论】:

  • 您现在运行查询时遇到什么样的错误?
  • 没有错误,我只需要两个驱动程序的行为一致,这样我就可以有一个代码路径来处理结果。

标签: python mysql postgresql psycopg2 mysql-python


【解决方案1】:

其实两者都可以。

db=MySQLdb.connect(host="localhost",user="anton",
        passwd="password",db="mytest", sql_mode="NO_BACKSLASH_ESCAPES")

会告诉mysqlto treat backslashes like the standard,所以like postgresql has been by default since 9.1。像这样设置sql_mode 可能不是你想要的,所以像sql_mode="TRADITIONAL,NO_BACKSLASH_ESCAPES" 这样的东西(注意它们之间没有空格,你会得到一个空格错误)会给你一个严格的sql_mode SQL 标准逃避行为。

也可以采用其他方式 - 您可以让 postgresql 在默认配置中以与 mysql 类似的方式操作(在 Ubuntu 20.04 上):

db=psycopg2.connect(host="localhost",user="anton",
        password="password",dbname="mytest", options='-c standard_conforming_strings=off')

基本上puts postgresql back in pre-9.1 mode 涉及反斜杠转义。

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 2021-11-16
    • 2015-09-21
    • 2011-11-09
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多