MySQLdb

MySQLdb-1.2.2 API documentation
http://mysql-python.sourceforge.net/MySQLdb-1.2.2/

• MySQLdb User Guide
• http://mysql-python.sourceforge.net/MySQLdb.html

使用 MySQLdb 或 SQLAlchemy 的时候,会发现表里的 Integer 字段被默认转换为了 long 类型。这种行为其实是 DB API 做的,即都是 MySQLdb 的错(假设你在使用这个 API 的话)。这是因为 MySQL 的 unsigned int 范围已经超出了 int 的上限,强行使用可能导致溢出。
但 int 的上限在 10 万亿以上,一般用作 ID 的话,在溢出风险和便利性的权衡上其实有很大空间。因此这里给出改变 DB API 默认转换规则的方法。
MySQLdb 从数据库中读出的数据本来都是字符串类型的,对数字和其他特定类型的转换是使用了相应的函数。每种字段类型的转换函数都是可配的。
当独立使用 MySQLdb 时,可以在 connect 函数中传入一个 conv 关键字参数来指定规则:
from MySQLdb.constants import FIELD_TYPE
from MySQLdb.converters import conversions

def__init__(self,m_host,m_port,m_user,m_password,m_dbname):
myconv=conversions.copy()
myconv.update({FIELD_TYPE.LONGLONG:int})
self.conn=MySQLdb.connect(host=m_host,
port=m_port,
user=m_user,
passwd=m_password,
db=m_dbname,
charset='utf8',
cursorclass=MySQLdb.cursors.DictCursor,
use_unicode=True,
conv=myconv
)

posted on 2017-07-20 16:03  JasonKwok  阅读(150)  评论(0)    收藏  举报

导航