【发布时间】:2020-05-28 14:41:00
【问题描述】:
简而言之,当向 sqlite3 数据库插入大整数时,例如 302140846680178689,它最终保存为 302140846680178700,我不知道为什么有时最后 1-2 位数字不正确。
我说有时是因为它不一致。例如,197918569894379520 将保留为 197918569894379520。
要重新创建的 Python 代码(我使用的是 3.7.6 64 位):
import sqlite3
conn = sqlite3.connect("example.db")
some_id = 302140846680178689
c = conn.cursor()
c.execute("CREATE TABLE example(one TEXT, two INTEGER, three BIG INT)")
c.execute("INSERT INTO example VALUES (?,?,?)", (some_id, some_id, some_id))
conn.commit()
conn.close()
生成的表格如下所示:
+--------------------+--------------------+--------------------+
| one(TEXT) | two(INTEGER) | three(BIG INT) |
+--------------------+--------------------+--------------------+
| 302140846680178689 | 302140846680178700 | 302140846680178700 |
+--------------------+--------------------+--------------------+
我期望整数和大整数的结果与3.1.1. of the docs 相同,似乎大整数只是整数的另一个名称,无论如何它都会是整数? Sqlite 将内部管理大小为引用INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
因此,整数的最大大小似乎是 2^63-1,足以容纳 302140846680178689 并且它似乎也不是来自模块的一些舍入错误,因为 print(int(float(302140846680178689)) - 302140846680178689) 给出了 -1 和但我的差是 11。
更新:根据 cmets 中的问题提供更多信息
print(sqlite3.version)
> 2.6.0
print(sqlite3.sqlite_version)
> 3.28.0
c.execute("SELECT typeof(two) FROM example;")
print(c.fetchall())
> [('integer',)]
在脚本末尾添加:
print(type(some_id))
> <class 'int'>
【问题讨论】:
-
我似乎无法在 Windows 10 上使用 SQLite 3.31.1 python 3.7 复制该问题。这可能是 SQLite 3.1.1 的问题吗?
-
在 Ubuntu 16.04 上也无法使用 python 3.5.2 和 sqlite 3.30.1 重现。
print(type(some_id))在运行时添加到该脚本的末尾会显示什么?还有来自 sqlite3 的SELECT typeof(two) FROM example;? -
您是在 Windows 还是 Linux 上运行代码?我最近发现,即使在 64 位 Windows 上,Python 实际上也会将
int视为 32 位:stackoverflow.com/questions/59914865/…
标签: python-3.x sqlite