This topic describes how to connect to OceanBase AI Database using Peewee and perform basic database operations, including creating tables, inserting data, updating data, and querying data.
Prerequisites
- You have installed Python 3.x and pip.
- You have installed OceanBase AI Database and created a user tenant.
Procedure
- Obtain the connection string for OceanBase AI Database.
- Install Peewee and the MySQL client library.
- Create a
test.pyfile and fill it with the database connection information. - Run the
test.pyfile.
Step 1: Obtain the connection string for OceanBase AI Database
Contact the deployment personnel or administrator of OceanBase AI Database to obtain the corresponding database connection string.
obclient -h$host -P$port -u$user_name -p$password -D$database_name
Parameter description:
$host: The IP address for connecting to OceanBase AI Database. For connections through OceanBase Database Proxy (ODP), use an ODP address; for direct connections, use the IP address of an OBServer node.$port: The port for connecting to OceanBase AI Database. For ODP connections, the default port is2883, which can be customized during ODP deployment; for direct connections, the default port is2881, which can be customized during OceanBase AI Database deployment.$database_name: The name of the database to access.Notice
The user connecting to the tenant must have the
CREATE,INSERT,UPDATE, andSELECTprivileges on this database. For more information about user privileges, see Privilege types.$user_name: The connection account for the tenant. For ODP connections, the common formats areusername@tenant_name#cluster_nameorcluster_name:tenant_name:username; for direct connections, the format isusername@tenant_name.$password: The account password.
For more information about the connection string, see Overview of connection methods.
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 Object-Relational Mapping (ORM) 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 commands to install Peewee and the MySQL client library.
pip install peewee pymysql
After installation, you can verify the installation by running the following command:
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: Write the test.py file and fill in the database connection information
Write the test.py file based on the information obtained in Step 1: Obtain the OceanBase AI Database connection string and fill in the database connection information.
Create a file named
test.py.Fill in the following content in the
test.pyfile and modify the database connection information as needed.The following example shows the content of the
test.pyfile: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 a database connection. db = MySQLDatabase( DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST, port=DB_PORT ) # Define 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 Database db.connect() # Create 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 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 the results.
Navigate to the directory where the
test.pyfile is located.Example:
cd D:\demo\demoRun the
test.pyfile.Example:
python test.pyThe return result is as follows:
John (20) Lucy (26) Tom (30)
Error handling
When using Peewee to connect to OceanBase AI Database, you may encounter various errors. The following are some common errors and their handling methods:
Connection error: If you cannot connect to the database, check whether the connection parameters are correct, including the hostname, port, username, password, and database name.
Permission error: If you encounter a permission-related error, ensure the user has sufficient permissions to perform the required operation.
SQL syntax error: If the SQL statement contains a syntax error, check whether the syntax of the SQL statement is correct.
Data type error: If the data type of the inserted value does not match the table definition, ensure that the data type of the inserted value is correct.
In Peewee, you can use try-except statements to catch and handle these errors, ensuring that the program handles errors gracefully instead of crashing directly. Additionally, you can use Python's logging module to record error information, which facilitates debugging and troubleshooting.
References
For more information about connecting to OceanBase AI Database, see Overview of connection methods.
For more information about creating a database, see CREATE DATABASE.