Loading [MathJax]/extensions/tex2jax.js
 Connection to PostgreSQL, Oracle&MySQL from Python – Obenkyolab

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

01
pip install psycopg2

Example

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)

Connect to MySQL

Package installation

01
pip install mysqlclient

Example

01
02
03
04
05
06
07
08
09
10
11
12
13
14
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.

01
pip install cx_Oracle

Example

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)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *