MST

星途 面试题库

面试题:Python实现MySQL数据批量插入与事务处理

使用Python和合适的MySQL连接库(如pymysql),编写一个函数,该函数接收一个列表,列表中的每个元素是一个包含三个值的元组,分别代表用户名、邮箱和注册时间。函数功能是将这些数据批量插入到MySQL数据库的'users'表中('users'表有'username', 'email', 'register_time'三个字段)。同时,要处理可能出现的数据库事务问题,确保数据的完整性,即如果部分数据插入失败,整个插入操作回滚。
17.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import pymysql


def insert_users_data(data_list):
    try:
        # 连接数据库
        connection = pymysql.connect(
            host='your_host',
            user='your_user',
            password='your_password',
            database='your_database',
            charset='utf8mb4'
        )
        with connection.cursor() as cursor:
            # SQL 插入语句
            sql = "INSERT INTO users (username, email, register_time) VALUES (%s, %s, %s)"
            # 执行批量插入
            cursor.executemany(sql, data_list)
        # 提交事务
        connection.commit()
    except pymysql.Error as e:
        # 发生错误时回滚
        if connection:
            connection.rollback()
        print(f"插入数据时发生错误: {e}")
    finally:
        # 关闭连接
        if connection:
            connection.close()

请将'your_host''your_user''your_password''your_database'替换为真实的数据库连接信息。