Python MySQL – mysql-connector 驱动(最佳实践)

Python MySQL – mysql-connector 驱动:初学者也能轻松上手数据库操作

你有没有遇到过这样的场景?写了一堆 Python 代码,数据存完就没了,下次运行又得重新输入?或者想做一个简单的用户管理系统,但不知道怎么把数据保存下来?这时候,数据库就派上用场了。

在众多数据库中,MySQL 是最流行的选择之一,尤其适合中小型项目。而 Python 想要和 MySQL 打交道,离不开一个关键工具:mysql-connector 驱动。它就像一座桥梁,让 Python 程序能与 MySQL 数据库自由通信。

这篇文章,我会带你从零开始,一步步掌握 Python MySQL – mysql-connector 驱动 的核心用法。不管你是刚学编程的新手,还是已经有点经验的中级开发者,都能找到实用的内容。


安装与环境准备

在使用任何工具之前,得先把它“请”进你的电脑。安装 mysql-connector 非常简单,只需一条命令:

pip install mysql-connector-python

这条命令会自动下载并安装最新版本的驱动。如果你用的是 Python 3.6 以上,基本不会遇到兼容问题。

💡 小贴士:建议使用虚拟环境(venv)来管理项目依赖,避免不同项目之间的包冲突。创建虚拟环境的命令是:

python -m venv myproject_env
myproject_env\Scripts\activate  # Windows
source myproject_env/bin/activate  # macOS/Linux

安装完成后,你可以通过以下代码测试是否成功:

import mysql.connector

print("mysql-connector 已成功导入")

如果看到输出 "mysql-connector 已成功导入",恭喜你,环境准备就绪!


建立数据库连接:打开通往数据世界的门

数据库就像一个巨大的电子档案柜,而连接就是打开柜门的钥匙。要操作数据库,第一步就是建立连接。

我们先创建一个简单的连接示例:

import mysql.connector

config = {
    'host': 'localhost',           # 数据库服务器地址,本地用 localhost
    'port': 3306,                  # MySQL 默认端口
    'user': 'your_username',       # 你的数据库用户名
    'password': 'your_password',   # 你的数据库密码
    'database': 'test_db'          # 要连接的数据库名
}

try:
    # 建立连接
    connection = mysql.connector.connect(**config)
    
    # 检查是否连接成功
    if connection.is_connected():
        print("✅ 成功连接到 MySQL 数据库")
        
        # 获取数据库信息
        db_info = connection.get_server_info()
        print(f"MySQL 服务器版本: {db_info}")
        
except mysql.connector.Error as err:
    print(f"❌ 连接失败: {err}")

finally:
    # 确保连接关闭,避免资源泄漏
    if 'connection' in locals() and connection.is_connected():
        connection.close()
        print("🔌 连接已关闭")

📌 关键点说明

  • host:通常是 localhost(本地),如果是远程服务器,填 IP 地址。
  • userpassword:必须与你 MySQL 中创建的用户一致。
  • database:要操作的数据库名称,如果不存在,会报错。
  • **config:将字典解包传入,代码更简洁。
  • is_connected():检查连接状态。
  • finally 块确保连接一定会关闭,这是良好编程习惯。

🔍 举个比喻:连接数据库就像去银行取钱。你得有银行卡(用户名/密码)、知道银行地址(host)、知道是哪个分行(database),才能顺利进门。


创建数据库与数据表:搭建数据的“骨架”

连接成功后,下一步就是建“地基”——创建数据库和表。你可以手动在 MySQL 客户端执行 SQL,但用 Python 也能完成。

import mysql.connector

config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'your_username',
    'password': 'your_password'
}

try:
    # 先连接到 MySQL 服务器(不指定 database)
    connection = mysql.connector.connect(**config)
    cursor = connection.cursor()

    # 创建数据库(如果不存在)
    create_db_query = "CREATE DATABASE IF NOT EXISTS test_db"
    cursor.execute(create_db_query)
    print("✅ 数据库 test_db 创建成功或已存在")

    # 切换到该数据库
    cursor.execute("USE test_db")

    # 创建数据表
    create_table_query = """
    CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL,
        email VARCHAR(100) UNIQUE,
        age INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    """
    cursor.execute(create_table_query)
    print("✅ 表 users 创建成功或已存在")

except mysql.connector.Error as err:
    print(f"❌ 操作失败: {err}")

finally:
    if 'connection' in locals() and connection.is_connected():
        cursor.close()
        connection.close()
        print("🔌 连接已关闭")

📌 重点解析

  • CREATE DATABASE IF NOT EXISTS:如果数据库不存在,就创建它,避免重复报错。
  • USE test_db:切换当前操作的数据库。
  • CREATE TABLE IF NOT EXISTS:同理,避免重复创建。
  • AUTO_INCREMENT:主键自动递增,像编号一样。
  • UNIQUE:邮箱不能重复,保证唯一性。
  • TIMESTAMP DEFAULT CURRENT_TIMESTAMP:自动记录创建时间。

📌 提示:第一次运行时,会看到“创建成功”;再次运行时,会提示“已存在”,这是正常现象。


插入数据:把数据“存”进数据库

现在表有了,下一步就是往里“填”数据。我们来插入一些测试用户。

import mysql.connector

config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'your_username',
    'password': 'your_password',
    'database': 'test_db'
}

try:
    connection = mysql.connector.connect(**config)
    cursor = connection.cursor()

    # 插入单条数据
    insert_query = """
    INSERT INTO users (name, email, age)
    VALUES (%s, %s, %s)
    """
    
    # 数据参数,用元组形式传入
    user_data = ("张三", "zhangsan@example.com", 25)

    # 执行插入
    cursor.execute(insert_query, user_data)
    connection.commit()  # 必须提交,否则数据不会真正保存

    print(f"✅ 成功插入一条数据,ID: {cursor.lastrowid}")

    # 插入多条数据
    multiple_users = [
        ("李四", "lisi@example.com", 30),
        ("王五", "wangwu@example.com", 28),
        ("赵六", "zhaoliu@example.com", 32)
    ]

    cursor.executemany(insert_query, multiple_users)
    connection.commit()

    print(f"✅ 成功插入 {cursor.rowcount} 条数据")

except mysql.connector.Error as err:
    print(f"❌ 插入失败: {err}")
    connection.rollback()  # 出错时回滚,防止数据不一致

finally:
    if 'connection' in locals() and connection.is_connected():
        cursor.close()
        connection.close()
        print("🔌 连接已关闭")

📌 关键点

  • %s 是占位符,防止 SQL 注入攻击(安全!)。
  • executemany() 可以批量插入,效率更高。
  • connection.commit():提交事务,是“确认保存”的动作。
  • cursor.lastrowid:获取最新插入记录的 ID。
  • cursor.rowcount:返回影响的行数。
  • rollback():出错时回滚,保证数据一致性。

🔄 比喻:插入数据就像往文件柜里放文件。你不按“保存”按钮(commit),文件就还在你手上,没真正放进柜子里。


查询数据:从数据库里“找”信息

数据存进去了,怎么拿出来看?查询就是“找人”或“查资料”的过程。

import mysql.connector

config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'your_username',
    'password': 'your_password',
    'database': 'test_db'
}

try:
    connection = mysql.connector.connect(**config)
    cursor = connection.cursor()

    # 查询所有用户
    select_query = "SELECT id, name, email, age, created_at FROM users"
    cursor.execute(select_query)

    # 获取所有结果
    results = cursor.fetchall()

    # 打印结果
    print("📋 所有用户信息:")
    print("ID\t姓名\t\t邮箱\t\t\t年龄\t创建时间")
    print("-" * 60)
    
    for row in results:
        print(f"{row[0]}\t{row[1]}\t\t{row[2]}\t\t{row[3]}\t{row[4]}")

except mysql.connector.Error as err:
    print(f"❌ 查询失败: {err}")

finally:
    if 'connection' in locals() and connection.is_connected():
        cursor.close()
        connection.close()
        print("🔌 连接已关闭")

📌 说明

  • fetchall():获取所有查询结果,返回一个列表,每个元素是一行数据(元组)。
  • fetchone():只取第一条记录。
  • fetchmany(n):取前 n 条。
  • row[0]row[1] 这种方式访问字段,索引从 0 开始。

🧠 小技巧:如果数据量大,不建议用 fetchall(),容易内存溢出。改用 fetchmany() 或游标遍历更安全。


更新与删除数据:修改和清理信息

数据不是一成不变的。用户改了名字?邮箱换了?那就要更新。不想要的记录?直接删除。

import mysql.connector

config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'your_username',
    'password': 'your_password',
    'database': 'test_db'
}

try:
    connection = mysql.connector.connect(**config)
    cursor = connection.cursor()

    # 更新数据:把张三的年龄改为 26
    update_query = "UPDATE users SET age = %s WHERE name = %s"
    cursor.execute(update_query, (26, "张三"))
    connection.commit()

    print(f"✅ 更新了 {cursor.rowcount} 条记录")

    # 删除数据:删除邮箱为 zhaoliu@example.com 的用户
    delete_query = "DELETE FROM users WHERE email = %s"
    cursor.execute(delete_query, ("zhaoliu@example.com",))
    connection.commit()

    print(f"✅ 删除了 {cursor.rowcount} 条记录")

except mysql.connector.Error as err:
    print(f"❌ 操作失败: {err}")
    connection.rollback()

finally:
    if 'connection' in locals() and connection.is_connected():
        cursor.close()
        connection.close()
        print("🔌 连接已关闭")

📌 注意

  • WHERE 条件是必须的,否则会更新/删除所有记录!
  • 使用占位符 %s,防止 SQL 注入。
  • cursor.rowcount 显示影响的行数。

⚠️ 警告:删除操作不可逆!建议先用 SELECT 查看要删的记录,确认无误再执行。


总结:从零开始掌握 Python MySQL – mysql-connector 驱动

通过这篇文章,我们一步步完成了:

  • 安装驱动并建立连接
  • 创建数据库和数据表
  • 插入、查询、更新、删除数据

你现在已经具备了使用 Python MySQL – mysql-connector 驱动 的基本能力。它不仅是连接 Python 与 MySQL 的桥梁,更是你构建数据驱动应用的第一步。

无论你是想做个学生信息管理,还是开发一个简单的博客后台,这些技能都能派上用场。记住:数据库不是“黑箱”,理解它、掌握它,你就能真正掌控数据。

最后,别忘了养成良好的习惯:连接后关闭、使用事务、避免 SQL 注入。这些细节,决定了你的代码是“能用”,还是“靠谱”。

现在,拿起你的键盘,去试试看吧!