Sup*_*d88 3 python sqlite python-3.x
我有一些信息要保存到一个 blob 字段中,然后保存到 sqlite 数据库中。
例如:
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)
Run Code Online (Sandbox Code Playgroud)
在这些情况下,输出是:
bytearray(b'Silicon Valley (TV series)\r\nFrom Wikipedia, the free encyclopedia\r\nSilicon Valley is an American television comedy series create')
Run Code Online (Sandbox Code Playgroud)
(我是从维基百科复制过来的)
我需要插入包含此信息的新记录。我有这个代码:
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')
Run Code Online (Sandbox Code Playgroud)
你能告诉我我的错误在哪里吗?
你的毯子try:..except掩盖了bytearray对象没有.tostring()方法的事实。即使有这样的方法,将字节转换为字符串在这里也是错误的方法。
不要使用字符串插值。使用 SQL 参数:
Cur.execute("insert into t_info (Primary_Key, Info_Value) values (1, ?)", (blob,))
Run Code Online (Sandbox Code Playgroud)
这让数据库库为您处理类型,同时保护您免受 SQL 注入攻击。
该?查询是一个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')]
Run Code Online (Sandbox Code Playgroud)
请注意,在查询时,该列作为bytes对象返回。