This topic describes how to connect to OceanBase Database by using peewee and perform basic database operations, including table creation, data insertion, data updating, and data query.
Prerequisites
- You have installed Python 3.x and pip.
- You have installed OceanBase Database and created a MySQL-compatible tenant.
Procedure
- Obtain the OceanBase Database connection string.
- Install peewee and the MySQL client library.
- Create the
test.pyfile and fill in the database connection information. - Run the
test.pyfile.
Step 1: Obtain the OceanBase Database connection string
Contact the deployment personnel or administrator of OceanBase Database to obtain the connection string.
obclient -h$host -P$port -u$user_name -p$password -D$database_name
The parameters are described as follows:
$host: the IP address for connecting to OceanBase Database. For connection through OceanBase Database Proxy (ODP), this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.$port: the port for connecting to OceanBase Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase Database is deployed.$database_name: the name of the database to be accessed.Notice
The user who connects to the tenant must have
CREATE,INSERT,UPDATE, andSELECTprivileges on the database. For more information about user privileges, see Privilege type in MySQL-compatible mode.$user_name: the account for connecting to the tenant. Common formats for ODP connection:username@tenant#cluster nameorcluster name:tenant:username. Format for direct connection:username@tenant.$password: the password of the account.
For more information about connection strings, see Connect to an OceanBase tenant by using OBClient.
Here is an example:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -Dtest
Step 2: Install peewee and the MySQL client library
peewee is a lightweight Python ORM (Object-Relational Mapping) library that provides a simple yet powerful API to simplify database operations. peewee supports multiple database backends, including MySQL, PostgreSQL, and SQLite.
Open the command prompt or PowerShell terminal, and run the following command to install peewee and the MySQL client library:
pip install peewee pymysql
After the installation, run the following command to verify the installation:
pip list | grep peewee
Note
peewee is a lightweight ORM library that provides a simple yet powerful API to simplify database operations. peewee supports multiple database backends, including MySQL, PostgreSQL, and SQLite.
Step 3: Create the test.py file and fill in the database connection information
Create the test.py file based on the information obtained in Step 1: Obtain the OceanBase Database connection string, and fill in the database connection information.
Create a file named
test.py.Add the following content to the
test.pyfile and modify the database connection information as needed.Here is an example of the content of the test.py file:
from peewee import * # Database connection information DB_USER = 'test_user001@mysql001' DB_PASSWORD = '******' DB_HOST = 'xxx.xxx.xxx.xxx' DB_PORT = 2881 DB_NAME = 'test' # Create the database connection db = MySQLDatabase( DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST, port=DB_PORT ) # Define the model class User(Model): name = CharField(max_length=50) age = IntegerField() class Meta: database = db table_name = 'users' def __str__(self): return f"{self.name} ({self.age})" # Connect to the database db.connect() # Create the table db.create_tables([User]) # Insert data User.create(name='John', age=20) User.create(name='Lucy', age=25) User.create(name='Tom', age=30) # Update data user = User.get(User.name == 'Lucy') user.age = 26 user.save() # Query data users = User.select() for user in users: print(user) # Close the database connection db.close()
Step 4: Run the test.py file
Open the command prompt or PowerShell terminal, and run the test.py file to query data and output results.
Go to the directory where the
test.pyfile is located.Here is an example:
cd D:\demo\demoRun the
test.pyfile.Here is an example:
python test.pyThe following result is returned:
John (20) Lucy (26) Tom (30)
Error handling
When you use peewee to connect to OceanBase Database, you may encounter various errors. The following are some common errors and their handling methods:
Connection errors: If you cannot connect to the database, check whether the connection parameters are correct, including the host name, port, username, password, and database name.
Privilege errors: If you encounter privilege-related errors, ensure that the user has sufficient privileges to perform the required operations.
SQL syntax errors: If the SQL statement has syntax errors, check whether the SQL syntax is correct.
Data type errors: If the data type of the inserted data does not match the table definition, ensure that the inserted data type is correct.
In peewee, you can use the try-except statement to catch and handle these errors, ensuring that the program handles errors gracefully instead of crashing. You can also use the Python logging module to record error information for debugging and troubleshooting.
References
For more information about connecting to OceanBase Database, see Connection methods overview.
For more information about creating a database, see CREATE DATABASE.