tencent cloud

TDSQL Boundless

Release Notes
Product Introduction
Overview
Scenarios
Product Architecture
Instance Types
Compatibility Notes
Usage specification recommendations
Kernel Features
Kernel Overview
Kernel Version Release Notes
Functionality Features
Performance Features
Billing
Billing Overview
Purchase Method
Pricing Details
Renewal
Overdue Payments
Refund
Getting Started
Creating an Instance
Connect to Instances
User Guide
Data Migration
Data Subscription
Instance Management
Parameter Configuration
Account Management
Security Group
Backup and Restoration
Database Auditing
Tag Management
Use Cases
Technical Evolution and Usage Practices of Online DDL
Lock Mechanism Analysis and Troubleshooting Practices
Data Intelligent Scheduling and Related Practices for Performance Optimization
TDSQL Boundless Selection Guide and Practical Tutorial
Developer Guide
Developer Guide (MySQL Compatibility Mode)
Developer Guide (HBase Compatibility Mode)
Performance Tuning
Performance Tuning Overview
SQL Tuning
DDL Tuning
Performance White Paper
Performance Overview
TPC-C Test
Sysbench Test
API Documentation
History
Introduction
API Category
Making API Requests
Instance APIs
Security Group APIs
Task APIs
Backup APIs
Rollback APIs
Parameter APIs
Database APIs
Data Types
Error Codes
General Reference
System Architecture
SQL Reference
Database Parameter Description
TPC-H benchmark data model reference
Error Code Information
Security and Compliance
FAQs
Agreements
Service Level Agreement
Terms of Service
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary

Python

PDF
フォーカスモード
フォントサイズ
最終更新日: 2026-03-06 18:48:24

Overview

TDSQL Boundless is highly compatible with MySQL protocols, and all Python database drivers that support MySQL can be adapted to TDSQL Boundless. This article details the mainstream drivers, features, usage examples, and considerations for TDSQL Boundless adaptation.
Driver Name
Type
Core strengths
Scenarios
mysql-connector-python
Official driver
Officially maintained by Oracle/MySQL, offers optimal compatibility with no additional dependencies.
Stability-focused scenarios without complex configurations

PyMySQL
Pure Python implementation
Lightweight and flexible, readable source code, simple installation, active community
Rapid development, small projects, scenarios requiring custom extensions
mysqlclient
C language extension
Optimal performance (20%-50% faster than pure Python drivers)
High concurrency OLTP scenarios, large-volume data read/write scenarios
aiomysql
asynchronous pure Python
Supporting asyncio asynchronous I/O, it is the preferred choice for high-concurrency asynchronous scenarios.
Projects using asynchronous Web frameworks such as FastAPI and aiohttp
SQLAlchemy
ORM framework (dependent on underlying drivers)
Masking differences in underlying drivers, supporting SQL abstraction and transaction management.
Medium-to-large projects, scenarios requiring cross-database compatibility

mysql-connector-python (Officially Recommended, Stable and Compatible)

Features

Officially produced by MySQL, it offers seamless protocol compatibility with TDSQL Boundless (MySQL-compatible).
Pure Python implementation, without dependencies on system MySQL libraries, facilitates cross-platform deployment.
Supports core features such as SSL connections, batch operations, and transaction management, meeting the financial-grade security requirements of TDSQL Boundless.

TDSQL Boundless Connection Example

import mysql.connector

# Configure database connection information (replace with your actual configuration)
db_config = {
"host": "10.10.10.10",
"user": "test",
"port": 7981,
"password": "test123",
"database": "test"
}
# Establish a connection + Create a single cursor (reuse this cursor for all SQL operations)
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor(buffered=True)

# 1. Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS test_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age TINYINT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")

# 2. Insert a row of data and commit the transaction
cursor.execute("INSERT INTO test_table (name, age) VALUES (%s, %s)", ("Tom", 22))
conn.commit()

# 3. Query data and print it.
cursor.execute("SELECT * FROM test_table WHERE name = %s", ("Tom",))
data = cursor.fetchone()
print("Query result:", data)

# Close cursor and connection
cursor.close()
conn.close()

PyMySQL (Lightweight and Flexible, Rapid Development)

Features

Pure Python implementation, dependency-free installation, beginner-friendly.
The syntax is highly compatible with mysql-connector-python, ensuring low migration costs.
Supports connection pooling, batch operations, active community maintenance, and convenient issue troubleshooting.

TDSQL Boundless Connection Example

import pymysql

# Configure database connection information (replace with your actual configuration)
db_config = {
"host": "10.10.10.10",
"user": "test",
"port": 7981,
"password": "test123",
"database": "test"
}

# Establish a connection + Create a cursor
conn = pymysql.connect(**db_config)
cursor = conn.cursor()

# 1. Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS test_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age TINYINT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")

# 2. Insert a row of data and commit the transaction
cursor.execute("INSERT INTO test_table (name, age) VALUES (%s, %s)", ("Tom", 22))
conn.commit()

# 3. Query data and print it.
cursor.execute("SELECT * FROM test_table WHERE name = %s", ("Tom",))
data = cursor.fetchone()
print("Query result:", data)

# Close cursor and connection
cursor.close()
conn.close()

mysqlclient (High-Performance Preferred Choice, High-Concurrency Scenarios)

Features

C wrapper for MySQL client library, significantly outperforming pure Python drivers in performance.
Compatible with the DB API 2.0 specification, and serves as the default recommended driver for Django and SQLAlchemy.
Supports large-scale data read/write and complex SQL execution, with high compatibility for TDSQL Boundless.

TDSQL Boundless Connection Example

import MySQLdb

# Configure database connection information (replace with your actual configuration)
db_config = {
"host": "10.10.10.10",
"user": "test",
"port": 7981,
"password": "test123",
"database": "test"
}


# Establish a connection + Create a cursor
conn = MySQLdb.connect(**db_config)
cursor = conn.cursor()

# 1. Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS test_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age TINYINT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")

# 2. Insert a row of data and commit the transaction
cursor.execute("INSERT INTO test_table (name, age) VALUES (%s, %s)", ("Tom", 22))
conn.commit()

# 3. Query data and print it.
cursor.execute("SELECT * FROM test_table WHERE name = %s", ("Tom",))
data = cursor.fetchone()
print("Query result:", data)

# Close cursor and connection
cursor.close()
conn.close()

aiomysql (Asynchronous Preferred Choice, Asynchronous High-Concurrency Scenarios)

Features

Based on PyMySQL encapsulation, supports asyncio asynchronous I/O with non-blocking connections.
Compatible with asynchronous frameworks such as FastAPI and aiohttp, supporting tens of thousands of concurrent connections in a single process.
Supports asynchronous connection pooling and asynchronous transactions, adapting to TDSQL Boundless distributed high-availability scenarios.

TDSQL Boundless Connection Example

import asyncio
import aiomysql

# Configure database connection information (replace with your actual configuration)
db_config = {
"host": "10.10.10.10",
"user": "test",
"port": 7981,
"password": "test123",
"db": "test"
}


async def main():
# 1. Establish an asynchronous connection
conn = await aiomysql.connect(**db_config)
# 2. Create an asynchronous cursor
cursor = await conn.cursor()

# 3. Create table
await cursor.execute("""
CREATE TABLE IF NOT EXISTS test_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age TINYINT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")

# 4. Insert a row of data and commit the transaction
await cursor.execute("INSERT INTO test_table (name, age) VALUES (%s, %s)", ("Tom", 22))
await conn.commit()

# 5. Query data and print it.
await cursor.execute("SELECT * FROM test_table WHERE name = %s", ("Tom",))
data = await cursor.fetchone()
print("Query result:", data)

# 6. Close cursor and connection
await cursor.close()
conn.close()

# Asynchronous startup method compatible with Python 3.6 (replace asyncio.run())
if __name__ == "__main__":
# 1. Obtain the default event loop
loop = asyncio.get_event_loop()
# 2. Run the asynchronous main function
loop.run_until_complete(main())
# 3. Close the event loop
loop.close()

SQLAlchemy (ORM framework, preferred choice for medium to large projects)

Features

High-level ORM framework that abstracts away underlying driver differences (compatible with mysqlclient/PyMySQL).
Supporting SQL abstraction, transaction management, and model mapping to reduce repetitive SQL coding.
Adapting to TDSQL Boundless sharding and read-write separation scenarios, supporting dynamic data source switching.

TDSQL Boundless Connection Example

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 1. Basic configuration: Create base class + database connection engine
Base = declarative_base()
# Connection string format: mysql+driver://username:password@host:port/database?charset
engine = create_engine("mysql+mysqldb://test:test123@10.10.10.10:7981/test?charset=utf8mb4")

# 2. Define the ORM model (corresponding to the test_table)
class TestTable(Base):
__tablename__ = "test_table" # Table name
id = Column(Integer, primary_key=True, autoincrement=True) # Auto-incrementing primary key
name = Column(String(50), nullable=False) # Username
age = Column(Integer, default=0) # Age

# 3. Create session (for database operations)
Session = sessionmaker(bind=engine)
session = Session()

# 4. Create table (if not exists)
Base.metadata.create_all(engine)

# 5. Insert a row of data
new_data = TestTable(name="Tom", age=22)
session.add(new_data)
session.commit() # Commit the transaction

# 6. Query data and print it.
query_data = session.query(TestTable).filter(TestTable.name == "Tom").first()
print("Query result:", (query_data.id, query_data.name, query_data.age))

# 7. Close the session
session.close()

ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック