PyMySQL小白必修课

1. 安装 PyMySQL

首先,你需要安装 PyMySQL。可以通过 pip 安装:

pip install pymysql

2. 连接数据库

要使用 PyMySQL,首先需要连接到 MySQL 数据库。以下是连接数据库的基本代码:

import pymysql

# 创建数据库连接
connection = pymysql.connect(
    host='localhost',       # 数据库主机地址
    user='root',            # 数据库用户名
    password='password',    # 数据库密码
    database='mydatabase'   # 数据库名称
)

print("数据库连接成功!")

3. 执行 SQL 查询

连接到数据库后,可以执行 SQL 查询。以下是查询数据的示例:

try:
    # 创建一个游标对象
    with connection.cursor() as cursor:
        # 执行 SQL 查询
        sql = "SELECT id, name, age FROM users"
        cursor.execute(sql)
        
        # 获取所有查询结果
        results = cursor.fetchall()
        
        # 打印查询结果
        for row in results:
            print(f"ID: {row['id']}, Name: {row['name']}, Age: {row['age']}")
finally:
    # 关闭数据库连接
    connection.close()

4. 插入数据

向数据库中插入数据的示例:

try:
    with connection.cursor() as cursor:
        # 插入数据的 SQL 语句
        sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
        cursor.execute(sql, ('John Doe', 30))
        
        # 提交事务
        connection.commit()
        print("数据插入成功!")
except pymysql.Error as e:
    print(f"插入数据时出错: {e}")
    # 回滚事务
    connection.rollback()
finally:
    connection.close()

5. 更新数据

更新数据库中已有数据的示例:

try:
    with connection.cursor() as cursor:
        # 更新数据的 SQL 语句
        sql = "UPDATE users SET age = %s WHERE name = %s"
        cursor.execute(sql, (31, 'John Doe'))
        
        # 提交事务
        connection.commit()
        print("数据更新成功!")
except pymysql.Error as e:
    print(f"更新数据时出错: {e}")
    connection.rollback()
finally:
    connection.close()

6. 删除数据

从数据库中删除数据的示例:

try:
    with connection.cursor() as cursor:
        # 删除数据的 SQL 语句
        sql = "DELETE FROM users WHERE name = %s"
        cursor.execute(sql, ('John Doe',))
        
        # 提交事务
        connection.commit()
        print("数据删除成功!")
except pymysql.Error as e:
    print(f"删除数据时出错: {e}")
    connection.rollback()
finally:
    connection.close()

7. 使用事务

PyMySQL 支持事务管理,可以确保一组操作要么全部成功,要么全部失败。以下是事务管理的示例:

try:
    with connection.cursor() as cursor:
        # 开始事务
        connection.begin()
        
        # 执行多个 SQL 操作
        sql1 = "INSERT INTO users (name, age) VALUES (%s, %s)"
        cursor.execute(sql1, ('Alice', 25))
        
        sql2 = "INSERT INTO users (name, age) VALUES (%s, %s)"
        cursor.execute(sql2, ('Bob', 28))
        
        # 提交事务
        connection.commit()
        print("事务提交成功!")
except pymysql.Error as e:
    print(f"事务执行时出错: {e}")
    # 回滚事务
    connection.rollback()
finally:
    connection.close()

总结

PyMySQL 是一个简单易用的库,用于在 Python 中与 MySQL 数据库交互。通过连接数据库、执行 SQL 查询、插入/更新/删除数据以及管理事务,你可以轻松完成各种数据库操作。希望这些示例能帮助你快速上手!

posted @ 2025-04-15 15:59  wei笑面对  阅读(278)  评论(0)    收藏  举报