[英]codec can't decode byte 0x89 Python
So I'm trying to integrate the raw image into my insert statement in Python所以我试图将原始图像整合到我在 Python 中的插入语句中
with open(filename, "rb") as imageFile:
im = open(filename, encoding="UTF-8")
state = "INSERT INTO T_DOCUMENT (BINCONTENT, DOCNAME) VALUES (" + im.read() + ", '.png')"
repo.Execute(state)
This is just my current code.这只是我当前的代码。 I tried various things I found (also searched on stack overflow) but I can't seem to find it.我尝试了我发现的各种东西(也在堆栈溢出上搜索)但我似乎找不到它。 I need to insert like the raw png file into the DB.我需要像原始 png 文件一样插入到数据库中。 I'm using Python 3.8我正在使用 Python 3.8
In the second line, you're trying to reopen a file you already have opened (as the variable imageFile
), and you're trying to read it as UTF-8-encoded text instead of as a binary.在第二行中,您试图重新打开一个您已经打开的文件(作为变量imageFile
),并且您试图将其读取为 UTF-8 编码文本而不是二进制文件。 Not surprisingly, the decoder hit a byte in your image that isn't valid UTF-8.毫不奇怪,解码器在您的图像中命中了一个无效字节 UTF-8。
I think what you want is to delete the second line and then use imageFile.read()
instead of im.read()
.我想你想要的是删除第二行,然后使用imageFile.read()
而不是im.read()
。 However, without knowing exactly what kind of database interface you're using, I would bet that this still won't work, because you're appending a bytes
object to a str
, and constructing a SQL statement with string operations is usually a bad idea .但是,在不知道您使用的是哪种数据库接口的情况下,我敢打赌这仍然行不通,因为您将bytes
object 附加到str
,并使用字符串操作构造 SQL 语句通常是不好的想法。 Use your interface's facility for parametric statements instead.请改用您的界面工具来处理参数语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.