Python 的 mysqldb 晦涩的文档

标签 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.

This documentation page说同样的话。但是那个“映射字典”应该是什么?我尝试了一些(大部分是随机的)事情,但只返回错误。更令人沮丧的是,虽然 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 不那么神秘。

最佳答案

我通过查看/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 表:对于 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)

关于Python 的 mysqldb 晦涩的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3327297/

相关文章:

Mysql:正向主机查找失败:未知主机

javascript - 将 json 数据对象从 php 传递到 javascript

mysql - 如何在不使用子查询、limit 和 top 子句的情况下在 mysql 中查找第二高的薪水

Python readlines Api 从串口访问时需要很长时间

python - 在 girdspec 的多列跨度子图中向左或向右对齐饼图

python - 从列表创建的表未显示所有元素

php - MySQL 查询在 PHP 中静默失败

python - 需要帮助理解列表理解表达式

python - 当我按下一个按钮时,两个按钮被按下,pygame

MYSQL STR_TO_DATE 未返回所需结果