1
5

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 3 years have passed since last update.

PythonからPostgreSQLを操作

Last updated at Posted at 2021-06-13

PythonからPostgreSQLを操作

■Postgreをwindows10にinstall

$ sudo apt update
$ sudo apt install postgresql

再起動

$ sudo /etc/init.d/postgresql restart

ユーザをpostgresに切り替え

$ sudo -u postgres -i

ユーザ(user)を作成.
パスワードを聞かれるので,パスワードを設定

$ createuser -d -U postgres -P user

user用データベースを作成


$ createdb userdb –encoding=UTF-8 –owner=user

■psycopg2をinstall
PostgreSQLを操作するためpsycpg2をinstall

$ pip install psycopg2

エラーが出力される場合は以下コマンドを実行

$ pip install psycopg2-binary
$ sudo apt install libpq-dev
$ sudo apt install postgresql-common

コマンドを実行したら再度インストール

$ pip install psycopg2

■DataBaseに接続

postgresConect.py
import psycopg2

connection = psycopg2.connect(
    host='localhost',
    database='userdb',
    user='user',
    password='password')

cur = connection.cursor()

cur.execute('SELECT * FROM mybook;')

results = cur.fetchall()

print(results)

cur.close()
connection.close()

参考
Windows10のWSL(Ubuntu)にPostgreSQLをインストールしたときのメモ
https://qiita.com/syutaro/items/d08c5c7cc24cddf7694c

psycopg2 インストールエラー
https://qiita.com/b2bmakers/items/d1b0db5966ac145b0e29

初心者がPythonを使ってPostgreSQL に接続する
https://qiita.com/arupaka__ri/items/5d4711c279d111622117

psycopg2 でよくやる操作まとめ
https://qiita.com/hoto17296/items/0ca1569d6fa54c7c4732

1
5
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
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?