简体   繁体   中英

psycopg2 vs MySQLdb backslash escaping behaviour

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())

Which outputs:

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

Basically, all I want is to be able to use the same insert sql (which I can't modify) and be able to get the same thing back for the text column using both db drivers by adding some parameter to the connection. I couldn't find how to control this behaviour on either, so am stuck.

Actually both are possible.

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

Will tell mysql to treat backslashes like the standard , and so like postgresql has been by default since 9.1 . Setting the sql_mode like this is probably not what you want though, so something like sql_mode="TRADITIONAL,NO_BACKSLASH_ESCAPES" (note there is no space between them, you get an error with a space) will give you a strict sql_mode with the SQL standard behaviour for escaping.

Going the other way is also possible - you can get postgresql to act in a similar way to mysql in the default config (on Ubuntu 20.04):

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

Which essentially puts postgresql back in pre-9.1 mode concerning backslash escaping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM