首页 > 解决方案 > 如何在 python sqlite3 中存储极长的整数?

问题描述

import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE TABLE "test_table" (number INTEGER)')
c.execute('INSERT INTO test_table (number) VALUES (?)', (9223372036854775807,))  # the max integer size sqlite3 supports'

# this works
c.execute("SELECT * FROM test_table")
print(c.fetchall())

# this does not. OverflowError: Python int too large to convert to SQLite INTEGER
c.execute('INSERT INTO test_table (number) VALUES (?)', (int(f'1{"0" * 100}'),))

我遇到了 sqlite3 的限制。我需要能够存储非常长的数字。长于 sqlite3 的限制 9223372036854775807。我想到的一个创可贴解决方案不是存储整数,而是存储一个字符串,这是传递的 python 整数的字符串形式,然后int()在查询时返回。但是我无法使用 ORDER BY 进行选择。否则,它按字母顺序排列,而不是按预期的数字顺序排列。是否有解决方案来存储更大的整数或使用 ORDER BY 选择而不手动查询整个数据库?

标签: pythonsqliteinteger

解决方案


如果您将整数零填充以使其具有相同的宽度(例如,如果您知道这是您的最大值,则为 100 位),那么字母顺序将与数字顺序匹配。


推荐阅读