Python的mysqldb模糊文档

eje*_*211 7 python mysql

Python模块mysqldb中有许多转义函数,我的文档我不明白,而我查找它们的努力没有透露任何内容.

>>> print _mysql.escape.__doc__
escape(obj, dict) -- escape any special characters in object obj
using mapping dict to provide quoting functions for each type.
Returns a SQL literal string.
Run Code Online (Sandbox Code Playgroud)

这个文档页面说的是同样的事情.但是那个"映射字典"应该是什么?我尝试了几个(大多是随机的)东西,只是回错了.更令人沮丧的是,虽然该escape_string()方法有效,但其文档字符串是:

>>> print _mysql.escape_string.__doc__
escape_string(s) -- quote any SQL-interpreted characters in string s.

Use connection.escape_string(s), if you use it at all.
_mysql.escape_string(s) cannot handle character sets. You are
probably better off using connection.escape(o) instead, since
it will escape entire sequences as well as strings.
Run Code Online (Sandbox Code Playgroud)

所以,我最好使用_mysql.escape(),是吗?嗯......好吧,但是怎么样?究竟是什么"映射字典"?PHP,至少在这方面,不那么神秘.

unu*_*tbu 7

我通过查看/usr/lib/pymodules/python2.6/MySQLdb/connections.py来了解它是如何调用的connection.escape.有点嗅闻导致 MySQLdb.converters.conversions.这是一个片段:

{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>}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

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'")
Run Code Online (Sandbox Code Playgroud)

PS.关于Bobby表:对于MySQLdb的正常使用,您不必手动转义参数.只需在调用时使用参数化参数cursor.execute,MySQLdb将自动为您引用参数.

例如:

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)
Run Code Online (Sandbox Code Playgroud)