2
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?

More than 5 years have passed since last update.

pg8000でのInsert文の発行

Posted at

概要

PythonからPostgreSQLにレコード追加する。

詳細

  • カーソルオブジェクト作成までは前回と同じ

インサート実行

Select文と同様にカーソルオブジェクトのexecuteメソッドを介して実行する。

sql = '''
INSERT INTO public.actors(
	id, name, yomigana, birth_place)
	VALUES (?, ?, ?, ?);
'''
cur.execute(sql, (3, '愛美', 'あいみ', '兵庫県',))

SQL部分にヒアドキュメントを使用できることもついでに確認

コミット

コミットはコネクションオブジェクトを介して実行する。

conn.commit()

自動コミットについて

デフォルトでは無効になっているが、以下のプロパティで有効に変更できる。

conn.autocommit = True

登録エラーについて

制約違反などでインサートに失敗した場合は以下のようにexecute実行行でエラーが発生する。

Traceback (most recent call last):
  File "C:\Users\***\***\Python\pgtest_DML.py", line 11, in <module>
    cur.execute(sql, (2, '大橋 彩香', 'おおはし あやか', '東京都',))
  File "C:\Users\***\Python3.6.6_64\lib\site-packages\pg8000\core.py", line 892, in execute
    self._c.execute(self, operation, args)
  File "C:\Users\***\Python3.6.6_64\lib\site-packages\pg8000\core.py", line 1921, in execute
    self.handle_messages(cursor)
  File "C:\Users\***\Python3.6.6_64\lib\site-packages\pg8000\core.py", line 1988, in handle_messages
    raise self.error
pg8000.core.IntegrityError: ('ERROR', 'ERROR', '23505', '重複キーが一意性制約"actors_pkey"に違反しています', 'キー (id)=(2) はすでに存在します。', 'public', 'actors', 'actors_pkey', 'nbtinsert.c', '434', '_bt_check_unique')

参考サイト

2
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
2
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?