将 python 字节对象写入 pgSQL bytea 列:字节字符串中的语法错误

问题描述

我正在编写一个工具,用于解码和分析测试车辆的 CAN 数据并将其与摄像机镜头一起显示

对于相机镜头,我使用 openCV 从提供的 .avi 文件获取帧,然后将其传递给 PIL 以降低质量并裁剪出图像的一个角落,其中使用 PyTesseract OCR 识别毫秒纪元时间戳。

接下来我想将图像作为 bytea 存储在我的 postgresql 数据库中。

我的代码是这样工作的: 这是上述代码的简化版本:

from io import BytesIO
from PIL import Image

# Image actually comes from cv2,in this case i just use a local jpg as example
image_path = 'meme.jpg'
img = Image.open(image_path)

# Dictionary for the processed Data
img_dict = {'TestDriveID': [],'TimeStamp':[],'Data':[]}

# here i store the image to a BytesIO(),reducing quality to 20%
buffer = BytesIO()
img.save(buffer,'JPEG',quality=20)

# the timestamp is actually obtained via ocr,here i use an arbitrary one.
timestamp = 1619435452340

# write the information to a dictionary to later pass it on to the uploading
# code and/or further uses
img_dict['TestDriveID'].append('test123')
img_dict['TimeStamp'].append(timestamp)
img_dict['Data'].append(buffer)

然后将此字典传递给应该上传图像的函数

import psycopg2
from sqlalchemy import create_engine
import io

# set up connection deFinition
sql_con_str = f'{driver}://{user}:{password}@{host}:{port}/{dbname}'
# create engine
sql_con = create_engine(sql_con_str)
# create a raw_connection object from the pgsql engine
raw_con = sql_con.raw_connection()
# define a cursor for the insertion
cur = raw_con.cursor()

for i in range(0,len(img_dict['TestDriveID'])):
    buffer = (img_dict['Data'][i])
    buffer.seek(0)

    cur.execute("""INSERT INTO images ("TestDriveID","TimeStamp","Data") 
                    VALUES ('%s',%s,%s)""" %(img_dict['TestDriveID'][i],img_dict['TimeStamp'][i],buffer.read()))
    raw_con.commit()

raw_con.close()

当我执行此代码时,出现以下异常:

---------------------------------------------------------------------------
SyntaxError                               Traceback (most recent call last)
<ipython-input-77-25a01ac78ad2> in <module>
     52     buffer.seek(0)
     53 
---> 54     cur.execute("""INSERT INTO svd_images ("TestDriveID","Data") 
     55                     VALUES ('%s',buffer.read()))
     56     raw_con.commit()

SyntaxError: Syntax error at or near "("
LINE 2: ...1\x15R\xd1\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:...
                                                             ^

我该如何解决这个问题? 或者有没有更有效的方法来做到这一点? 我计划在这样的时间插入 45000 张图像。 (30 分钟视频,25fps,27kb/帧)

预先感谢,我希望我提供了足够的信息,我对此很陌生。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...