This topic describes how to connect to OceanBase Database by using a Python driver.
In a Python 3.x environment
PyMySQL is a library in Python 3.x for connecting to MySQL servers. OceanBase Database also supports PyMySQL.
PyMySQL implements Python Database API Specification 2.0 and contains a pure-Python MySQL client library.
For more information about PyMySQL, see PyMySQL documentation and API Reference.
Install PyMySQL
You must install PyMySQL before you can use it. To download the installation package, click here.
You can install PyMySQL by using one of the following two methods:
Use the command-line tool
python3 -m pip install PyMySQLCompile from source code
git clone https://github.com/PyMySQL/PyMySQL cd PyMySQL/ python3 setup.py install
Use PyMySQL
You can run the following command to set the connection object:
conn = pymysql.connect(
host="localhost",
port=2881,user="root",
passwd="",
db="testdb"
)
Example:
#!/usr/bin/python3
import pymysql
conn = pymysql.connect(host="localhost", port=2881,
user="root", passwd="", db="testdb")
try:
with conn.cursor() as cur:
cur.execute('SELECT * FROM cities')
ans = cur.fetchall()
print(ans)
finally:
conn.close()
In a Python 2.x environment
MySQL-python is a library in Python 2.x for connecting to MySQL servers. OceanBase Database also supports MySQL-python.
MySQL-python allows you to connect to and operate OceanBase Database by using MySQLdb. MySQLdb is an interface that allows you to connect to a MySQL database from Python. It implements the Python Database API Specification 2.0 and is built based on the MySQL C API.
For more information about MySQL-python, see MySQL-python documentation and Project description on Github.
Install MySQL-python
You can use pip to install MySQL-python in a Python 2.x environment.
pip install MySQL-python
Use MySQL-python
You can run the following command to set the connection object:
conn= MySQLdb.connect(
host='127.0.0.1',
port = 2881,
user='root',
passwd='',
db ='testdb'
)
Example:
#!/usr/bin/python2
import MySQLdb
conn= MySQLdb.connect(
host='127.0.0.1',
port = 2881,
user='root',
passwd='',
db ='testdb'
)
try:
cur = conn.cursor()
cur.execute('SELECT * from cities')
ans = cur.fetchall()
print(ans)
finally:
conn.close()