从or字段(列)中检索“大”或“小”数字时,这似乎是pypyodbc和 Access ODBC 驱动程序之间的兼容性问题,其中“大”表示Single
Double
Single
小数点左侧有效数字超过 6 位的值,或
Double
小数点左侧超过 14 位有效数字的值
“小”是指
Single
小数点右侧有超过 6 个零的值,或
Double
小数点右侧有超过 14 个零的值
当数字表示为“正常”小数时(即,不是科学计数法)。
重新创建的代码:
import pypyodbc
cnxn = pypyodbc.connect(
r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
r"DBQ=C:\Users\Public\Database1.accdb")
crsr = cnxn.cursor()
try:
crsr.execute("DROP TABLE tblJunk")
except pypyodbc.ProgrammingError as pe:
# ignore "table does not exist"
if pe.value[0] != '42S02':
raise
crsr.execute("CREATE TABLE tblJunk (ID INT PRIMARY KEY, DoubleField DOUBLE, SingleField SINGLE)")
crsr.execute("INSERT INTO tblJunk (ID, DoubleField) VALUES (1, 12345678.9)")
crsr.execute("SELECT DoubleField, SingleField FROM tblJunk WHERE ID=1")
row = crsr.fetchone()
print(row)
# prints: (12345678.9, None)
crsr.execute("UPDATE tblJunk SET SingleField = DoubleField WHERE ID=1")
crsr.execute("SELECT DoubleField, SingleField FROM tblJunk WHERE ID=1")
row = crsr.fetchone()
# ValueError: could not convert string to float: E+7
解决方法1:对于Single
值,使用该CDbl()
函数可以避免错误:
crsr.execute("SELECT DoubleField, CDbl(SingleField) AS foo FROM tblJunk WHERE ID=1")
row = crsr.fetchone()
print(row)
# prints: (12345678.9, 12345679.0)
解决方法 2:使用该CStr()
函数将值作为字符串返回,然后将其转换为浮点数(适用于Single
和Double
):
crsr.execute("SELECT DoubleField, CStr(SingleField) AS foo FROM tblJunk WHERE ID=1")
row = crsr.fetchone()
print(row)
# prints: (12345678.9, u'1.234568E+07')
print(float(row[1]))
# prints: 12345680.0
解决方法 3:使用pyodbc而不是 pypyodbc。