Overview
Scenarios
Product Architecture
Instance Types
Compatibility Notes
Usage specification recommendations
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 |
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 tablecursor.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 transactioncursor.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 connectioncursor.close()conn.close()
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 cursorconn = pymysql.connect(**db_config)cursor = conn.cursor()# 1. Create tablecursor.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 transactioncursor.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 connectioncursor.close()conn.close()
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 cursorconn = MySQLdb.connect(**db_config)cursor = conn.cursor()# 1. Create tablecursor.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 transactioncursor.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 connectioncursor.close()conn.close()
import asyncioimport 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 connectionconn = await aiomysql.connect(**db_config)# 2. Create an asynchronous cursorcursor = await conn.cursor()# 3. Create tableawait 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 transactionawait 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 connectionawait cursor.close()conn.close()# Asynchronous startup method compatible with Python 3.6 (replace asyncio.run())if __name__ == "__main__":# 1. Obtain the default event looploop = asyncio.get_event_loop()# 2. Run the asynchronous main functionloop.run_until_complete(main())# 3. Close the event looploop.close()
from sqlalchemy import create_engine, Column, Integer, Stringfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_base# 1. Basic configuration: Create base class + database connection engineBase = declarative_base()# Connection string format: mysql+driver://username:password@host:port/database?charsetengine = 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 nameid = Column(Integer, primary_key=True, autoincrement=True) # Auto-incrementing primary keyname = Column(String(50), nullable=False) # Usernameage = 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 datanew_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 sessionsession.close()
フィードバック