如何将Python十进制转换为SQLite数字?

wti*_*ing 13 python sqlite numeric decimal

我有一个程序,它以JSON格式读取财务数据并将其插入到SQLite数据库中.问题是当我将它插入SQLite数字列时,它似乎不喜欢小数对象.

我之前发现这个问题已得到解答,但答案已经过时,据我所知,SQLite现在有一种名为numeric的货币数据类型.

现在作为一种解决方法我将十进制值存储为文本,但是可以将其存储为数字吗?我是否坚持将小数转换为字符串的开销,反之亦然,以便进行数据库插入和财务计算?

unu*_*tbu 23

sqlite3允许您注册一个适配器(透明地转换DecimalsTEXT插入时)和转换器(透明地转换TEXTDecimals获取时).

以下是来自文档的示例代码的轻微修改版本:

import sqlite3
import decimal
D=decimal.Decimal

def adapt_decimal(d):
    return str(d)

def convert_decimal(s):
    return D(s)

# Register the adapter
sqlite3.register_adapter(D, adapt_decimal)

# Register the converter
sqlite3.register_converter("decimal", convert_decimal)

d = D('4.12')

con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(d decimal)")

cur.execute("insert into test(d) values (?)", (d,))
cur.execute("select d from test")
data=cur.fetchone()[0]
print(data)
print(type(data))

cur.close()
con.close()
Run Code Online (Sandbox Code Playgroud)

产量

4.12
<class 'decimal.Decimal'>
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案不再有效。根据 sqlite3 文档,转换器函数始终以“字节”格式调用,因此为了使代码在 Python 3.8 中工作,您必须在定义上调用“D(s.decode('utf-8'))” `convert_decimal` 函数的。 (2认同)