微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将 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.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?