Connection to PostgreSQL, Oracle&MySQL from Python
Overview
There are some samples to connect PostgreSQL, Oracle, MySQL from Python.
How to connect PostgreSQL
Package installation
pip install psycopg2
Example
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)
Connect to MySQL
Package installation
pip install mysqlclient
Example
import MySQLdb
HOST = 'your_host'
PORT = 3306 #Not str but 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の場合
Package installation ※Oracle client is also necessary adding to this.
pip install cx_Oracle
Example
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)