This topic describes how to connect to OceanBase Cloud using SQLAlchemy 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 registered an OceanBase Cloud account and created a cluster instance and an OceanBase Cloud tenant in MySQL-compatible mode. For more information, see Create a cluster instance and Create a tenant.
Procedure
- Obtain the connection string for OceanBase Cloud.
- Install the SQLAlchemy 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 Cloud
Log in to the OceanBase Cloud console. On the instance list page, expand the target instance's information. Under the target tenant, select Connect > Get connection string.
For more detailed operations, see Get connection string.
Fill in the corresponding information in the following URL based on your created OceanBase Cloud database.
obclient -h$host -P$port -u$user_name -p$password -D$database_nameParameter description:
$host: The connection address for OceanBase Cloud, for example,t********.********.oceanbase.cloud.$port: The connection port for OceanBase Cloud, default is 3306.$database_name: The name of the database to access.
Note
The user connecting to the tenant must have the
CREATE,INSERT,UPDATE, andSELECTprivileges on this database. For more information about account privileges, see Create and manage accounts.$user_name: The account used to access the database.$password: The password for the account.
Example:
obclient -h t********.********.oceanbase.cloud -P3306 -u 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 an SQL toolkit and an ORM system that simplifies database operations. SQLAlchemy supports multiple database backends, including MySQL, PostgreSQL, SQLite, and others.
Open a command prompt or PowerShell terminal and run the following command to install the SQLAlchemy library.
pip install sqlalchemy mysqlclient
After installation, you can verify its success with the following command:
pip list | grep SQLAlchemy
Note
SQLAlchemy is a powerful ORM library that provides two usage modes: Core and ORM. Core offers an SQL expression language, while ORM provides object-relational mapping functionality. This example primarily uses the ORM mode.
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 Cloud 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 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 = 'mysql001' DB_PASSWORD = '******' DB_HOST = 't********.********.oceanbase.cloud' DB_PORT = 3306 DB_NAME = 'test' # Create a database connection URL DATABASE_URL = f"mysql+mysqldb://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}" # Create Engine engine = create_engine(DATABASE_URL) # Create base class Base = declarative_base() # Define 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 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 Session session.close()
Step 4: Run the test.py file
Open a 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.pyExample output:
<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 OceanBase Cloud, 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 a permission-related error occurs, ensure the user has sufficient privileges to perform the required operation.
SQL syntax error: If an SQL statement contains a syntax error, check whether the SQL statement is syntactically correct.
Data type error: If the data type of the inserted value does not match the table definition, ensure the inserted data type is correct.
In your code, you can use try-except statements to catch and handle these errors, ensuring the program handles them gracefully instead of crashing directly. Additionally, you can use the logging module to record error information, which facilitates debugging and troubleshooting.
References
- For more information about connecting to OceanBase Cloud, see Overview of connection methods.