开发者社区 问答 正文

在python 中如何向postgresql 中插入图片???报错

请教各位大神如何 在python 中如何向postgresql 中插入图片??

python代码如下:

>>> import psycopg2

>>> conn = psycopg2.connect(database='aa',user='aaa')

>>> cur = conn.cursor()

>>> cur.execute('create table test_image(name varchar(50), image_date bytea)')

>>> f = open('C:/Users/John/Desktop/aa.jpg','rb').read()

以上步骤OK,但是将二进制数据f 插入数据库就不知道怎么办了

>>> cur.execute("insert into test_image values('aaa1'," + f + ")")报错

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.DataError: 閿欒:  invalid byte sequence for encoding "UTF8": 0xff

mysqldb 里好像是的excape_string()方法,我没有试过,psycopg应该怎么办??


展开
收起
爱吃鱼的程序员 2020-06-22 21:58:58 612 分享 版权
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
    数据库格式CREATETABLEpublic.pic_data(    p_idbigintNOTNULL,   p_frontagebytea,)conn=psycopg2.connect(host='localhost',user='pic',password='123456',database='pic')cursor=conn.cursor()img_buffer=None#openimagewithopen("1.jpg",'rb')asimg_open:img_buffer=img_open.read()insert_sql="INSERTINTOservices_picture(p_id,p_frontage)values(%s,%s)"params=psycopg2.Binary(img_buffer)cursor.execute(insert_sql,(i,params))conn.commit()cursor.close()conn.close()
    2020-06-22 21:59:17
    赞同 展开评论