如何在Python中将字节串添加到SQLite数据库?

编程语言 2026-07-08

我想在Python的 SQLite数据库中添加一个字节串。
我尝试将其格式化为字符串再转换回来,但无论使用哪种编码,都无法得到相同的整数值。

我几乎尝试了我能找到或想到的几乎所有方法,但都没有起作用。
我找到的教程要么过时,要么对我来说太难理解。

我也尝试过使用Blob,但这会引发一个 sqlite3.OperationalError

#lets just pretend I'm trying to make a database including pictures from diffrent locations
import sqlite3

#my database is formatted like this (integer, Blob, Text, Text)

with open("image.png", "rb") as file:
    f = file.read()

con = sqlite3.connect("database.db")

cur = con.cursor()

cur.execute(f"Insert into {Table} Values(1,{f}, Park, New-York")

我也尝试过这个,但也报错:

import sqllib3

with open("image.png", "rb") as file:
    f = file.read()
    b = bytearray(f)

[...] #same as before

cur.execute(f"Insert into {table} Values(1,{b}, Park, New-York")

解决方案

问题在于你直接将原始二进制数据插入到SQL字符串中。SQLite无法解析嵌入SQL语句中的任意字节数据。

相反,使用参数化查询,将字节数据作为参数传递。sqlite3 模块会自动将其存储为BLOB。

import sqlite3

with open("image.png", "rb") as file:
    image_data = file.read()

con = sqlite3.connect("database.db")
cur = con.cursor()

cur.execute(
    "INSERT INTO MyTable VALUES (?, ?, ?, ?)",
    (1, image_data, "Park", "New York")
)

con.commit()
con.close()

在你原始的查询中:

cur.execute(f"Insert into {Table} Values(1,{f}, Park, New-York)")

有几个问题:

  • f 包含原始字节,这不是有效的SQL语法。
  • ParkNew-York 应该被引号括起来,作为字符串字面量。
  • 使用f-strings将值插入SQL语句是不安全的,可能导致SQL注入漏洞。

对于BLOB列,将 bytes 对象作为查询参数(?)传递,而不是将其嵌入到SQL语句中。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章