Python连接MySQL数据库的代码主要分为连接数据库、执行SQL操作和关闭连接三个步骤。以下是具体实现:
一、安装数据库驱动
推荐使用pymysql
或mysql-connector-python
库,可通过以下命令安装:
pip install pymysql
# 或
pip install mysql-connector-python
二、连接数据库
-
基础连接示例
import pymysql # 连接参数 config = { 'host': 'localhost', 'user': 'root', 'password': 'password', 'database': 'test_db', 'port': 3306, 'charset': 'utf8mb4' } # 建立连接 conn = pymysql.connect( **config) cursor = conn.cursor()
-
使用上下文管理器自动管理连接
from contextlib import contextmanager import logging @contextmanager def get_connection(): conn = None try: conn = pymysql.connect( **config, cursorclass=pymysql.cursors.DictCursor) yield conn except Exception as e: logging.error(f"数据库连接错误: {str(e)}") raise finally: if conn: conn.close() # 使用示例 with get_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT VERSION()") print(cursor.fetchone())
三、执行SQL操作
- 创建表
create_table_sql = """ CREATE TABLE IF NOT EXISTS students (