打印存储在MySQL数据库中的不同值

2024-09-28 22:58:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在myISAM的MySQL表中,我有一个整数值ex.011。当我在Python中查询时,它会输出值11,去掉数字前的0。它应该打印存储在DB ex.011而不是11中的确切值。有什么帮助吗?在


Tags: dbmysql数字数值myisam
2条回答

可能,在这种情况下,简单的零填充可以吗?在

>>> print str(11).zfill(3)
011

据我所知,这是数字的附加部分。如果它的长度不是常量,则需要将DB中的数据类型更改为VARCHAR。在

您的列是一个int,因此MySQLdb在查询结果中返回一个整数值。但是,我认为您应该能够编写一个mySQLdb结果集包装器(或者可能找到其他人已经编写过的包装器),它检查结果集的列上的标志集并将其转换为适当的字符串。在

看看cursor.description和{}以及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

相关问题 更多 >