我有一个在 Python 代码之外定义的 MySQL 数据库。我使用反射将其放入 SQLAlchemy,因此我没有任何可以修改的类定义。我不必担心失去精度,并且我对 Python 中的结果进行了一些算术运算,因此我宁愿不必手动将一堆值转换为 float 或 Decimal。
import sqlalchemy as sa
eng = sa.create_engine("mysql+pymysql://user:passwd@server/database")
eng.execute("create table if not exists foo (x double not null)")
eng.execute("insert into foo (x) values (0.1)")
md = sa.MetaData(bind=eng)
md.reflect()
foo = md.tables["foo"]
res = eng.execute(foo.select())
row = res.fetchone()
print(type(row.x))
print(repr(foo.c.x.type))
Output:
<class 'decimal.Decimal'>
DOUBLE
使用来自的建议这个帖子,并且在我设置之前不使用反射表asdecimal
属性,我可以获得浮点数而不是小数。
import sqlalchemy as sa
eng = sa.create_engine("mysql+pymysql://chiptest:fryisthedevil@database/bench_drylake")
eng.execute("create table if not exists foo (x double not null)")
eng.execute("insert into foo (x) values (0.1)")
md = sa.MetaData(bind=eng)
md.reflect()
foo = md.tables["foo"]
# this needs to happen before any queries
for table in md.tables.values():
for column in table.columns.values():
if isinstance(column.type, sa.Numeric):
column.type.asdecimal = False
res = eng.execute(foo.select())
row = res.fetchone()
print(type(row.x))
print(repr(foo.c.x.type))
Output:
<class 'float'>
DOUBLE(asdecimal=False)
注意:如果在设置之前对反射表进行查询asdecimal = False
, column.type
仍然显示为DOUBLE(asdecimal=False)
,但值的类型仍然是Decimal
。我猜这是因为 SQLAlchemy 正在进行某种缓存,但我现在不会确定这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)