This topic describes how to use SQLAlchemy to connect to OceanBase Database and perform basic database operations, including table creation, data insertion, data updating, and data querying.
Prerequisites
- You have installed Python 3.x and pip.
- You have installed OceanBase Database and created a MySQL-compatible tenant.
Procedure
- Obtain the connection string of OceanBase Database.
- Install the SQLAlchemy library.
- Write a
test.pyfile and enter the database connection information. - Run the
test.pyfile.
Step 1: Obtain the connection string of OceanBase Database
Contact the deployment personnel or administrator of OceanBase Database to obtain the corresponding database connection string.
obclient -h$host -P$port -u$user_name -p$password -D$database_name
Parameters:
$host: the IP address for connecting to OceanBase Database. For connection through OceanBase Database Proxy (ODP), use the IP address of an ODP. For direct connection, use 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 used to connect to the tenant must have the
CREATE,INSERT,UPDATE, andSELECTprivileges on the database. For more information about user privileges, see Privilege types in MySQL mode.$user_name: the tenant connection account. For connection through ODP, the format isusername@tenant name#cluster nameorcluster name:tenant name:username. For direct connection, the format isusername@tenant name.$password: the account password.
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 the SQLAlchemy library
SQLAlchemy is one of the most popular Object Relational Mapping (ORM) libraries in Python. It provides a SQL toolkit and an ORM system to simplify database operations. SQLAlchemy supports multiple database backends, including MySQL, PostgreSQL, and SQLite.
Open the command prompt or PowerShell, and run the following command to install the SQLAlchemy library.
pip install sqlalchemy mysqlclient
After the installation is complete, run the following command to verify whether the installation was successful:
pip list | grep SQLAlchemy
Note
SQLAlchemy is a powerful ORM library that provides two usage modes: Core and ORM. Core provides a SQL expression language, while ORM provides object-relational mapping functionality. The examples in this topic use the ORM mode.
Step 3: Write the test.py file and enter the database connection information
Write the test.py file based on the information obtained in Step 1: Obtain the connection string of OceanBase Database and enter the database connection information.
Create a file named
test.py.Enter the following content into the
test.pyfile and modify the database connection information as needed.Here is an example of the
test.pyfile content:from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 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 URL DATABASE_URL = f"mysql+mysqldb://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}" # Create an engine engine = create_engine(DATABASE_URL) # Create a base class Base = declarative_base() # Define a model class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) age = Column(Integer) def __repr__(self): return f"<User(id={self.id}, name='{self.name}', age={self.age})>" # Create a table Base.metadata.create_all(engine) # Create a session Session = sessionmaker(bind=engine) session = Session() # Insert data new_users = [ User(name='John', age=20), User(name='Lucy', age=25), User(name='Tom', age=30) ] session.add_all(new_users) session.commit() # Update data user = session.query(User).filter_by(name='Lucy').first() if user: user.age = 26 session.commit() # Query data users = session.query(User).all() for user in users: print(user) # Close the session session.close()
Step 4: Run the test.py file
Open the command prompt or PowerShell terminal, run the test.py file, query data, and output the result.
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 return result is as follows:
<User(id=1, name='John', age=20)> <User(id=2, name='Lucy', age=26)> <User(id=3, name='Tom', age=30)>
Error handling
When using SQLAlchemy to connect to the OceanBase database, you may encounter various errors. Below are some common errors and their solutions:
Connection errors: If you are unable to connect to the database, check whether the connection parameters are correct, including the hostname, port, username, password, and database name.
Permission errors: If you encounter permission-related errors, ensure that the user has sufficient privileges to perform the required operations.
SQL Syntax errors: If there are syntax errors in your SQL statements, verify that 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 data type being inserted is correct.
In your code, you can use try-except statements to catch and handle these errors, ensuring that the program can handle errors gracefully instead of crashing. Additionally, you can use the logging module to record error information, which helps with debugging and troubleshooting.
References
For more information about how to connect to OceanBase Database, see Overview of connection methods.
For more information about how to create a database, see CREATE DATABASE.