python - 打印存储在 MySQL DB 中的不同值

标签 python mysql sqlalchemy

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

最佳答案

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

查看 cursor.descriptioncursor.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/

相关文章:

mysql - MySQL 5.2如何备份和恢复?

php - Mysql 查询选择具有不同列值的结果

python - sqlalchemy 连接失败但 cx_oracle 成功

Python SQLAlchemy 模拟

python - 如果传入选项,则将值设置为 argparse 中的变量

python - 如何从字典中删除最旧的元素?

Python:Pandas Grouper()函数时间戳选择

mysql - 计数和子选择

python - SQLAlchemy + Postgres + Python 完整性错误

python - mod_wsgi 错误 - class.__dict__ 在受限模式下不可访问