Python的mysqldb文档模糊不清

7 投票
3 回答
3372 浏览
提问于 2025-04-16 01:47

在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.

这个文档页面也说了类似的内容。但是那个“映射字典”里应该放什么呢?我试了几样(大多是随便找的东西),结果只得到了错误信息。更让人沮丧的是,虽然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.

所以,我是不是应该使用_mysql.escape()呢?嗯...好吧,但这怎么用呢?那个“映射字典”到底是什么?相比之下,PHP在这方面就简单多了。

3 个回答

0

试试这个 mysqldb 教程。我自己也用过这个教程来学习 mysqldb。

2

其实,你最好使用更高级的接口,也就是 MySQLdb。(可以查看用户指南

_mysql 这些函数其实只是 C 语言接口的封装。它们主要是一些实现细节,类似于在 PHP 文档中根本不会出现的东西。开发者故意把它们的文档写得很少,就是为了不让人们不必要地使用这些函数。而且,你可以参考 MySQL 的C API 文档,那里有更完整的对应函数说明。

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>}

你可以这样使用它:

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'")

附注:关于Bobby Tables的问题:在正常使用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)

撰写回答