Jeg lærte dette ved at kigge i /usr/lib/pymodules/python2.6/MySQLdb/connections.py for at se, hvordan det kaldte connection.escape
. Lidt snusning fører tilMySQLdb.converters.conversions
. Her er et uddrag:
{0: <class 'decimal.Decimal'>,
1: <type 'int'>,
...
<type 'dict'>: <built-in function escape_dict>,
<type 'NoneType'>: <function None2NULL at 0xae9717c>,
<type 'set'>: <function Set2Str at 0xae9709c>,
<type 'str'>: <function Thing2Literal at 0xae971b4>,
<type 'tuple'>: <built-in function escape_sequence>,
<type 'object'>: <function Instance2Str at 0xae971ec>,
<type 'unicode'>: <function Unicode2Str at 0xae9710c>,
<type 'array.array'>: <function array2Str at 0xae9725c>,
<type 'bool'>: <function Bool2Str at 0xae97294>}
Du kan bruge det sådan her:
import MySQLdb
import MySQLdb.converters
import datetime
now=datetime.datetime.now()
connection=MySQLdb.connect(
host=HOST,user=USER,passwd=PASS,db=MYDB)
print(connection.escape((1,2,now),MySQLdb.converters.conversions))
# ('1', '2', "'2010-07-24 19:33:59'")
PS. Angående Bobby Tables:For normal brug af MySQLdb behøver du ikke manuelt at undslippe argumenter. Brug blot parametriserede argumenter, når du kalder cursor.execute
, og MySQLdb vil automatisk citere argumenterne for dig.
For eksempel:
sql='insert into students (name,grade,date) values (%s, %s, %s)'
args=("Robert'); DROP TABLE Students; --",60,now) # no manual quotation necessary
cursor=connection.cursor()
cursor.execute(sql,args)