【问题标题】:Incorrect value for big integers sqlite大整数 sqlite 的值不正确
【发布时间】: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


【解决方案1】:

好吧,讽刺的是我自己并没有测试我通过手动查询发布的代码。

我不想为了查看数据而手动使用代码进行查询,而是我使用 sqlite 查看器,更具体地说是https://sqliteonline.com/

现在我通过代码手动查询进行了测试,它返回了正确的值,但是在该查看器中打开数据库由于某种原因返回了不正确的值(我真的没有想到查看器有问题,因为它实际上只是在查询SELECT * FROM example,现在我什至尝试了它的不同版本,但仍然是相同的错误结果。

编辑来自开发者的回复:查看器在库“SQLite.js”上工作,JavaScript 中的最大数字是 9007199254740991,因此任何数字都将四舍五入。

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 2018-07-20
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多