批量插入开启一个事务的代码演示
时间: 2023-08-30 21:06:19 浏览: 46
以下是一个使用 Python 和 MySQL 数据库实现批量插入并开启事务的示例代码:
```python
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标
mycursor = mydb.cursor()
# 开启事务
mycursor.execute("START TRANSACTION")
# 批量插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
# 提交事务
mydb.commit()
print(mycursor.rowcount, "记录已插入。")
```
在这个示例中,我们使用 `executemany()` 方法实现批量插入数据,使用 `execute()` 方法开启和提交事务。注意,在开启事务后,所有插入操作都必须使用同一个游标对象,否则事务将无法提交成功。