gpt4 book ai didi

python 3.x 将字节数组写入sqlite3 blob字段

转载 作者:行者123 更新时间:2023-11-30 23:08:03 25 4
gpt4 key购买 nike

我有一些信息想要保存到 SQLite 数据库的 Blob 字段中。

例如:

out = [83, 105, 108, 105, 99, 111, 110, 32, 86, 97, 108, 108, 101, 121, 32, 40, 84, 86, 32, 115, 101, 114, 105, 101, 115, 41, 13, 10, 70, 114, 111, 109, 32, 87, 105, 107, 105, 112, 101, 100, 105, 97, 44, 32, 116, 104, 101, 32, 102, 114, 101, 101, 32, 101, 110, 99, 121, 99, 108, 111, 112, 101, 100, 105, 97, 13, 10, 83, 105, 108, 105, 99, 111, 110, 32, 86, 97, 108, 108, 101, 121, 32, 105, 115, 32, 97, 110, 32, 65, 109, 101, 114, 105, 99, 97, 110, 32, 116, 101, 108, 101, 118, 105, 115, 105, 111, 110, 32, 99, 111, 109, 101, 100, 121, 32, 115, 101, 114, 105, 101, 115, 32, 99, 114, 101, 97, 116, 101]

blob = bytearray(out)
print(blob)

在这些情况下,输出是:

bytearray(b'Silicon Valley (TV series)\r\nFrom Wikipedia, the free encyclopedia\r\nSilicon Valley is an American television comedy series create')

(我从维基百科复制了它)

我需要插入包含此信息的新记录。我有这个代码:

import sqlite3

out = [83, 105, 108, 105, 99, 111, 110, 32, 86, 97, 108, 108, 101, 121, 32, 40, 84, 86, 32, 115, 101, 114, 105, 101, 115, 41,
13, 10, 70, 114, 111, 109, 32, 87, 105, 107, 105, 112, 101, 100, 105, 97, 44, 32, 116, 104, 101, 32, 102, 114, 101, 101,
32, 101, 110, 99, 121, 99, 108, 111, 112, 101, 100, 105, 97, 13, 10, 83, 105, 108, 105, 99, 111, 110, 32, 86, 97, 108,
108, 101, 121, 32, 105, 115, 32, 97, 110, 32, 65, 109, 101, 114, 105, 99, 97, 110, 32, 116, 101, 108, 101, 118, 105, 115
, 105, 111, 110, 32, 99, 111, 109, 101, 100, 121, 32, 115, 101, 114, 105, 101, 115, 32, 99, 114, 101, 97, 116, 101]

blob = bytearray(out)
print(blob)

Con = sqlite3.connect('info.db')
Cur = Con.cursor()

Cur.execute("create table t_info (Primary_Key INTEGER PRIMARY KEY ASC, Info_Value BLOB )")

try:
Cur.execute("insert into t_info (Primary_Key, Info_Value) values (1, X'" + blob.tostring() + "')")
except:
print('error')

你能告诉我我的错误在哪里吗?

最佳答案

你的一揽子try:.. except掩盖了bytearray对象没有.tostring()方法的事实。即使有这样的方法,将字节转换为字符串在这里也是错误的方法。

不要使用字符串插值。使用 SQL 参数:

Cur.execute("insert into t_info (Primary_Key, Info_Value) values (1, ?)", (blob,))

这可以让数据库为您处理类型,同时保护您免受 SQL 注入(inject)攻击。

查询中的?是一个SQL参数;第二个参数中的每个值都用于填充参数。

演示:

>>> Cur.execute("insert into t_info (Primary_Key, Info_Value) values (1, ?)", (blob,))
<sqlite3.Cursor object at 0x10a0ca810>
>>> Con.commit()
>>> Cur = Con.cursor()
>>> Cur.execute('select * from t_info')
<sqlite3.Cursor object at 0x10a0caab0>
>>> list(Cur)
[(1, b'Silicon Valley (TV series)\r\nFrom Wikipedia, the free encyclopedia\r\nSilicon Valley is an American television comedy series create')]

请注意,在查询时,该列将作为 bytes 对象返回。

关于python 3.x 将字节数组写入sqlite3 blob字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31941454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com