在带有 myISAM 的 MySQL 表中,我有一个整数值 ex.011。当我在 Python 中查询时,它会打印值 11,删除数字前的 0。它应该打印存储在 DB ex 中的确切值。 011 而不是 11。有什么帮助吗?
最佳答案
您的列是一个int
,因此MySQLdb 在查询结果中返回一个整数值。但是,我认为您应该能够编写一个 mySQLdb 结果集包装器(或者可能找到其他人已经编写的包装器)来检查结果集列上设置的标志并适本地转换为字符串。
查看 cursor.description
和 cursor.description_flags
以及 PEP-249。我认为(即我还没有真正尝试过)以下内容应该可以帮助您开始:
def get_result_set_with_db_specified_formatting(cursor):
integer_field_types = (MySQLdb.constants.FIELD_TYPE.TINY,
MySQLdb.constants.FIELD_TYPE.SHORT,
MySQLdb.constants.FIELD_TYPE.LONG,
MySQLdb.constants.FIELD_TYPE.LONGLONG,
MySQLdb.constants.FIELD_TYPE.INT24)
rows = cursor.fetchall()
for row in rows:
for index, value in enumerate(row):
value = str(value)
if (cursor.description[index][1] in integer_field_types
and cursor.description_flags[index] & MySQLdb.constants.FLAG.ZEROFILL):
if len(value) < cursor.description[index][2]:
value = ('0' * (cursor.description[index][2] - len(value))) + value
row[index] = value
return rows
关于python - 打印存储在 MySQL DB 中的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840195/