在postgresql数据库中插入一个映像



我想知道如何将图像"byta"插入postgreSql数据库的表中?我已经在论坛上搜索了几个小时,看到同一个问题发布了几十次,但还没有找到一个答案。我所看到的只是如何将.jpeg插入到一个旧列中,这不是我所需要的。

这是数据库表:

create table category  (
"id_category" SERIAL,
"category_name" TEXT,
"category_image" bytea,
constraint id_cat_pkey primary key ("id_category"))without oids;

当我添加新行时,它不起作用:

insert into category(category_name,category_image) values('tablette', lo_import('D:image.jpg'));

如果列类型为byta,则可以简单地使用'pg_read_binary_file'。

示例:pg_read_binary_file('/path-to-image/')

检查pg_read_binary_file 的postgresql文档

上面的例子都不适合我,除此之外,我还需要同时添加许多图像。

完整的工作示例(python 3(及其解释:

使用get_binary_array,我们将图像(或文件(的值作为二进制数组,使用其路径和文件名作为参数(例如:'/home/Pictures/blue.png'(

使用send_files_to_postgresql,我们一次发送所有图像。

我之前创建的数据库有一个顺序的"id",它将自动递增(但你可以使用自己的自制id(和一个字节的"image"字段

import psycopg2
def get_binary_array(path):
    with open(path, "rb") as image:
        f = image.read()
        b = bytes(f).hex()
        return b
def send_files_to_postgresql(connection, cursor, file_names):
    query = "INSERT INTO table(image) VALUES (decode(%s, 'hex'))"
    mylist = []
    for file_name in file_names:
        mylist.append(get_binary_array(file_name))
    try:
        cursor.executemany(query, mylist)
       
        connection.commit()  # commit the changes to the database is advised for big files, see documentation
        count = cursor.rowcount # check that the images were all successfully added
        print (count, "Records inserted successfully into table")
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
def get_connection_cursor_tuple():
    connection = None
    try:
        params = config()
        print('Connecting to the PostgreSQL database...')
        connection = psycopg2.connect(**params)
        cursor = connection.cursor()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    return connection, cursor
connection, cursor = connect_db.get_connection_cursor_tuple()
img_names = ['./blue.png', './landscape.jpg']
send_files_to_postgresql(connection, cursor, img_names)
insert into category(category_name,category_image) values('tablette', bytea('D:image.jpg'));

如果列类型为字节,则上述解决方案有效

insert into category(category_name,category_image) values('tablette', lo_import('D:image.jpg'));

如果列类型为oid,即Blob ,则上述解决方案有效

insert into category(category_name,category_image) values('tablette',decode('HexStringOfImage',hex));

上述解码函数采用两个参数。第一个参数是图像的HexString。第二个参数默认为十六进制。Decode函数将hexString转换为字节,并存储在postgres中的byta数据类型列中。

类似于这个函数(从这里稍微调整一下(的东西可以工作。

create or replace function img_import(filename text)
  returns void
  volatile
  as $$
    declare
        content_ bytea;
        loid oid;
        lfd integer;
        lsize integer;
    begin
        loid := lo_import(filename);
        lfd := lo_open(loid,131072);
        lsize := lo_lseek(lfd,0,2);
        perform lo_lseek(lfd,0,0);
        content_ := loread(lfd,lsize);
        perform lo_close(lfd);
        perform lo_unlink(loid);
    insert into category values
    ('tablette',
    content_);
    end;
$$ language plpgsql

select * from img_import('D:image.jpg');一样使用它或者如果喜欢,可以重写到过程。

创建以下函数:

create or replace function bytea_import(p_path text, p_result out bytea) 
                       language plpgsql as $$
    declare
      l_oid oid;
    begin
      select lo_import(p_path) into l_oid;
      select lo_get(l_oid) INTO p_result;
      perform lo_unlink(l_oid);
    end;$$;

并像这样使用:

insert into table values(bytea_import('C:1.png'));

对于Linux用户,这是如何将路径添加到映像

insert into blog(img) values(bytea('/home/samkb420/Pictures/Sam Pics/sam.png'));
create table images (imgname text, img bytea);

insert into images(imgname,img) values ('MANGO', pg_read_binary_file('path_of_image')::bytea);

使用SQL工作台-数据库资源管理器-插入一行并跟随对话。。。

在此处输入图像描述

相关内容

最新更新