OceanBase logo

OceanBase

A unified distributed database ready for your transactional, analytical, and AI workloads.

Product Overview
DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Resources

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS

OceanBase Cloud

OceanBase Database

Tools

Connectors and Middleware

QUICK START

OceanBase Cloud

OceanBase Database

BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Company

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

International - English
中国站 - 简体中文
日本 - 日本語
Sign In
Start on Cloud

OceanBase

A unified distributed database ready for your transactional, analytical, and AI workloads.

Product Overview
DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS
OceanBase CloudOceanBase Database
ToolsConnectors and Middleware
QUICK START
OceanBase CloudOceanBase Database
BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

Start on Cloud
编组
All Products
    • Databases
    • iconOceanBase Database
    • iconOceanBase Cloud
    • iconOceanBase Tugraph
    • iconInteractive Tutorials
    • iconOceanBase Best Practices
    • Tools
    • iconOceanBase Cloud Platform
    • iconOceanBase Migration Service
    • iconOceanBase Developer Center
    • iconOceanBase Migration Assessment
    • iconOceanBase Admin Tool
    • iconOceanBase Loader and Dumper
    • iconOceanBase Deployer
    • iconKubernetes operator for OceanBase
    • iconOceanBase Diagnostic Tool
    • iconOceanBase Binlog Service
    • Connectors and Middleware
    • iconOceanBase Database Proxy
    • iconEmbedded SQL in C for OceanBase
    • iconOceanBase Call Interface
    • iconOceanBase Connector/C
    • iconOceanBase Connector/J
    • iconOceanBase Connector/ODBC
    • iconOceanBase Connector/NET
icon

OceanBase Database

SQL - V4.3.5

    Download PDF

    OceanBase logo

    The Unified Distributed Database for the AI Era.

    Follow Us
    Products
    OceanBase CloudOceanBase EnterpriseOceanBase Community EditionOceanBase seekdb
    Resources
    DocsBlogLive DemosTraining & CertificationTicket
    Company
    About OceanBaseTrust CenterLegalPartnerContact Us
    Follow Us

    © OceanBase 2026. All rights reserved

    Cloud Service AgreementPrivacy PolicySecurity
    Contact Us
    Document Feedback
    1. Documentation Center
    2. OceanBase Database
    3. SQL
    4. V4.3.5
    iconOceanBase Database
    SQL - V 4.3.5
    SQL
    KV
    • V 4.6.0
    • V 4.4.2
    • V 4.3.5
    • V 4.3.3
    • V 4.3.1
    • V 4.3.0
    • V 4.2.5
    • V 4.2.2
    • V 4.2.1
    • V 4.2.0
    • V 4.1.0
    • V 4.0.0
    • V 3.1.4 and earlier

    Connect to OceanBase Database by using SQLAlchemy

    Last Updated:2026-05-11 02:24:09  Updated
    share
    What is on this page
    Prerequisites
    Procedure
    Step 1: Obtain the connection string of OceanBase Database
    Step 2: Install the SQLAlchemy library
    Step 3: Write the test.py file and enter the database connection information
    Step 4: Run the test.py file
    Error handling
    References

    folded

    share

    This topic describes how to connect to OceanBase Database by using SQLAlchemy, and how to perform basic database operations such as creating tables, inserting data, updating data, and querying data.

    Prerequisites

    • You have installed Python 3.x and pip.
    • You have installed OceanBase Database and created a MySQL tenant.

    Procedure

    1. Obtain the connection string of OceanBase Database.
    2. Install the SQLAlchemy library.
    3. Write a test.py file and enter the database connection information.
    4. Run the test.py file.

    Step 1: Obtain the connection string of OceanBase Database

    Obtain the database connection string from the deployment personnel or administrator of OceanBase Database.

    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 is 2883, which can be customized when ODP is deployed. For direct connection, the default value is 2881, 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, and SELECT privileges 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 is username@tenant name#cluster name or cluster name:tenant name:username. For direct connection, the format is username@tenant name.

    • $password: the password of the account.

    For more information about the connection string, 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 SQL tools and an ORM system to simplify database operations. SQLAlchemy supports multiple database backends, including MySQL, PostgreSQL, and SQLite.

    Open the command prompt or PowerShell terminal, and run the following command to install the SQLAlchemy library.

    pip install sqlalchemy mysqlclient
    

    After the installation is completed, run the following command to check 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 SQL expression language, and ORM provides object-relational mapping functionality. This topic uses ORM as the main method.

    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.

    1. Create a file named test.py.

    2. Enter the following content into the test.py file and modify the database connection information as needed.

      Here is a sample content of the test.py file:

      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 tables
      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.

    1. Go to the directory where the test.py file is located.

      Here is an example:

      cd D:\demo\demo
      
    2. Run the test.py file.

      Here is an example:

      python test.py
      

      The 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 you use SQLAlchemy to connect to OceanBase Database, various errors may occur. The following table describes some common errors and their solutions.

    1. Connection error: If you cannot connect to the database, check whether the connection parameters, including the host name, port, username, password, and database name, are correct.

    2. Privilege error: If you encounter a privilege error, make sure that the user has sufficient privileges to perform the required operation.

    3. SQL syntax error: If there is a syntax error in your SQL statement, check whether the syntax is correct.

    4. Data type error: If the data type of the inserted data does not match that defined in the table, make sure that the data type is correct.

    In your code, you can use the try-except statement to capture and handle these errors, ensuring that the program can handle errors gracefully instead of crashing. You can also use the logging module to record error information for 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.

    Previous topic

    MySQL-connector-python
    Last

    Next topic

    Connect to OceanBase Database with Django
    Next
    What is on this page
    Prerequisites
    Procedure
    Step 1: Obtain the connection string of OceanBase Database
    Step 2: Install the SQLAlchemy library
    Step 3: Write the test.py file and enter the database connection information
    Step 4: Run the test.py file
    Error handling
    References