直接上代码:
import psycopg2
import os
def dump_image():
"""
要求:
表已经存在
path路径及文件名不允许有中文
创建表时存文件的字段应该指定bytea类型,例如:create table image (id serial, data bytea);
"""
#将path目录下的所有图片导入PG
path = 'D:\huge\\' # 反斜杠(\)转义输出,或写成 r'D:\huge\'
conn = psycopg2.connect(database="postgres", user="chen", password="123456", host="127.0.0.1")
cur = conn.cursor()
for dirpath, dirnames, filenames in os.walk(path):
for filepath in filenames:
# 字符串拼接成需要的格式
file_path = "'" + path + filepath + "'"
print(file_path)
cur.execute('''insert into image(data) select pg_read_binary_file({});'''.format(file_path))
conn.commit()
conn.close()
图片信息:
初始化表,表为空:
运行程序:
结果:
可以看到图片已经导入PG