This topic describes how to connect to OceanBase Database by using Python drivers.
Use PyMySQL in a Python 3.x environment
If you use Python 3.x, you can connect to a MySQL database server by using 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:
Run the following command in a CLI tool:
python3 -m pip install PyMySQLCompile the 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 object to connect:
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()
Use MySQL-python in a Python 2.x environment
If you use Python 2.x, you can connect to a MySQL database server by using MySQL-python.
MySQL-python allows you to connect to and operate on an OceanBase database by using MySQLdb. MySQLdb is an interface that allows you to connect a Python application to a MySQL database. 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 the Project description on Github.
Install MySQL-python
Before you use pip to install MySQL-python, ensure that Python 2.x is installed on your computer.
pip install MySQL-python
Use MySQL-python
You can run the following command to set the object to connect:
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()