Pythonからデータベース接続(PostgreSQL,Oracle,MySQL)
目的
pythonからデータベースに接続するコードをすぐ忘れるので、書き留める
PostgreSQLの場合
パッケージインストール
01 | pip install psycopg2 |
コード
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | import psycopg2 HOST = 'your_host' PORT = '5432' DB_NAME = 'your_db_name' USER = 'your_user_name' PASSWORD = 'your_password' conn = psycopg2.connect( "host=" + HOST + " port=" + PORT + " dbname=" + DB_NAME + " user=" + USER + " password=" + PASSWORD ) cur = conn.cursor() cur.execute( "select version()" ) rows = cur.fetchall() cur.close() conn.close() print (rows) |
MySQLの場合
パッケージインストール
01 | pip install mysqlclient |
コード
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | import MySQLdb HOST = 'your_host' PORT = 3306 #文字列ではなくint DB_NAME = 'your_db_name' USER = 'your_user_name' PASSWORD = 'your_password' conn = MySQLdb.connect( user = USER, passwd = PASSWORD, host = HOST, db = DB_NAME,port = PORT) cur = conn.cursor() cur.execute( "select version()" ) rows = cur.fetchall() conn.close() print (rows) |
Oracleの場合
パッケージインストール ※別途Oracle clientが必要
01 | pip install cx_Oracle |
コード
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 | import cx_Oracle HOST = 'your_host' PORT = '1521' DB_NAME = 'your_db_name' USER = 'your_user_name' PASSWORD = 'your_password' SERVICE_NAME = 'your_service_name' tns = cx_Oracle.makedsn(HOST, PORT, service_name = SERVICE_NAME) conn = cx_Oracle.connect(USER,PASSWORD,tns) cur = conn.cursor() cur.execute( "select * from v$version" ) rows = cur.fetchall() cur.close() conn.close() print (rows) |