【问题标题】:Insert image into PostgresSQL将图像插入 PostgresQL
【发布时间】:2019-12-05 15:40:09
【问题描述】:

我试图插入一个 postgres 数据库。 这是查询

INSERT INTO public.tblcast(
    castname, castimage)
    VALUES ('Henry Cavill',bytea('E:\Cast\henry.jpg'));

但是显示错误

ERROR:  invalid input syntax for type bytea
LINE 3:  VALUES ('Henry Cavill',bytea('E:\Cast\henry.jpg'));
                                      ^
SQL state: 22P02
Character: 81ERROR:  invalid input syntax for type bytea

castimage 列的数据类型为 bytea。

【问题讨论】:

  • 你也可以分享一下列的类型 - castimage 吗?
  • castimage bytea

标签: python sql postgresql image


【解决方案1】:

编辑:我回答这个问题已经有一段时间了,但我想我弄错了,虽然 OP 似乎对答案很满意,但我相信它需要一些 cmets。感谢 Daniel Vérité!

lo_import

使用lo_import,您可以使用绝对路径导入文件,但它返回OID 类型的对象,因此您需要更改列数据类型 - stud3nt 在另一个答案中也提出了建议。

INSERT INTO public.tblcast(castname, castimage)
VALUES ('Henry Cavill',lo_import('server_path_to_file'));

如果您无法在导入前将文件放入服务器(就像我们大多数人一样),您可以在控制台中使用\lo_import 工具和psql

echo "\lo_import '/client_path_to_file' \\\ INSERT INTO  public.tblcast VALUES ('Henry Cavil', :LASTOID)" | psql yourdb

lo_export

psql yourdb -c "SELECT lo_export(castimage, 'path_to_export_file') FROM tblcast;"

pg_read_file(不太灵活):

这个generic file access function 提供了读取服务器中文件的可能性。但是,它仅限于数据目录路径。如果您想知道它在系统中的位置,请尝试以下命令:

SHOW data_directory

这将是一种如何使用它的方法 - 正如 Mike Pur 的回答中所示:

INSERT INTO public.tblcast(castname, castimage)
VALUES ('Henry Cavill',pg_read_file('path to file')::bytea);

【讨论】:

  • 那行得通。它现在在相应的字段中显示二进制数据。
【解决方案2】:

使用 pg_read_file

INSERT INTO public.tblcast(
    castname, castimage)
    VALUES ('Henry Cavill',pg_read_file('E:\Cast\henry.jpg')::bytea);

【讨论】:

  • invalid byte sequence for encoding "UTF8": 0xff 显示此错误。
【解决方案3】:

使用lo_import('E:\Cast\henry.jpg') 而不是bytea('E:\Cast\henry.jpg')

【讨论】:

  • You will need to rewrite or cast the expression. 我在创建表格时使用了 bytea。我有机会在不更改数据类型的情况下插入吗?
猜你喜欢
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 2014-07-01
  • 2016-08-29
  • 2019-11-20
相关资源
最近更新 更多