This topic provides a code example on how to connect a Python application to OceanBase Database.
Python3.x series (using PyMySQL)
PyMySQL is a library for connecting to the MySQL server in Python3.x.
PyMySQL follows the Python Database API v2.0 specification and includes a pure-Python MySQL client library.
For more information about PyMySQL, see the official documentation and API reference documentation.
Install PyMySQL
Go to the PyMySQL page to download and install PyMySQL.
There are two methods of installing PyMySQL:
Use the command line
python3 -m pip install PyMySQLCompile from source code
git clone https://github.com/PyMySQL/PyMySQL cd PyMySQL/ python3 setup.py install
Use PyMySQL
Run the following command to set the connect 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()
Python2.x series (using MySQL-python)
MySQL-python is a library for connecting to the MySQL server in Python2.x.
MySQL-python is installed to connect and operate OceanBase Database using MySQLdb. MySQLdb is an interface for a Python application to connect to the MySQL database. It implements the Python database API specification V2.0 and is based on the MySQL C API.
For more information about MySQL-python, see the official documentation and GitHub documentation.
Install MySQL-python
First, ensure that you have a Python2.x environment on your computer, and then use pip to install MySQL-python.
pip install MySQL-python
Use MySQL-python
Run the following command to set the connect 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()