python3 插入与读取图片 到 postgresql中

一、表结构如下:

CREATE TABLE public.article_image
(
    art_id integer NOT NULL,
    art_image bytea,
    CONSTRAINT article_image_pkey PRIMARY KEY (art_id)
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public.article_image
    OWNER to default user;

二、读取

import psycopg2

import io

from PIL import Image

conn=psycopg2.connect(database='Db',user='myuser',password='mypassword',host='localhost')

cursor=conn.cursor()

cursor.execute("select * from article_image where art_id=2")

for row in cursor:

data=row[1]

image=Image.open(io.BytesIO(data))

image.save("/home/user/22.png")

cursor.close()

conn.close()

三、插入

conn = psycopg2.connect(host='localhost',user='pic',password='123456', database='pic')
cursor = conn.cursor()
img_buffer = None
# open image
with open("1.jpg", 'rb') as img_open:
     img_buffer = img_open.read()
insert_sql = "INSERT INTO services_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()

 

以上语法都测试过,只作为示例展示。

 

 

你可能感兴趣的:(python,数据库)