Reputation: 953
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.
Upvotes: 2
Views: 470
Reputation: 953
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.
Upvotes: 2