1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PostgreSQL: バイナリーデータの取り扱い

Last updated at Posted at 2024-05-06

こちらのページを参考にしました。
Aurora(PostgreSQL)のbytea列にバイナリデータをpythonでインサートする

PostgreSQL への接続情報

User: scott
Password: tiger123
DataBase: db_pdf

テーブルの用意

create_table.sql
create table table_pdf
(
    id  int primary key,
    pdf bytea not null
);
$ psql -U scott db_pdf < create_table.sql
CREATE TABLE

データの挿入

fuji.pdf というデータを挿入します。

pdf_insert.py
#! /usr/bin/python

import psycopg2
import psycopg2.extras

conn = psycopg2.connect("host=localhost port=5432 dbname=db_pdf user=scott password=tiger123")

cur = conn.cursor()
img = open('fuji.pdf', 'rb').read()

idx = 102

cur.execute("INSERT INTO table_pdf (id,pdf) values (%d,%s)" %
    (idx,psycopg2.Binary(img),))

conn.commit()
cur.close()
conn.close()

実行

./pdf_insert.py

データの取り出し

pdf_retrieve.py
#! /usr/bin/python

import psycopg2
import psycopg2.extras

conn = psycopg2.connect("host=localhost port=5432 dbname=db_pdf user=scott password=tiger123")

cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("SELECT pdf FROM table_pdf;")

row = cur.fetchone()
pic = row['pdf']

f = open('out01.pdf', 'wb')
f.write(pic)
f.close()
cur.close()
conn.close()

実行

./pdf_retrieve.py

csvファイルへの出力

db_pdf=> \copy table_pdf to '/tmp/t001.csv' delimiter ',' csv header;
COPY 1

テーブルからデータの削除

db_pdf=> delete from table_pdf;
DELETE 1

csv ファイルを取り込んで見る

db_pdf=> \copy table_pdf from '/tmp/t001.csv' delimiter ',' csv header;
COPY 1
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?