如何一次批量添加多条记录值
时间: 2024-11-09 19:31:34 浏览: 9
在数据库操作中,一次性批量添加多条记录通常是为了提高效率,避免频繁的单条插入操作。下面是针对不同数据库系统的一些示例:
1. **MySQL** (使用Python的`mysql-connector-python`库):
```python
import mysql.connector
data = [
("value1", "value2"),
("value3", "value4"),
# 更多数据...
]
cnx = mysql.connector.connect(user='username', password='password',
host='localhost',
database='database_name')
cursor = cnx.cursor()
sql = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
cursor.executemany(sql, data)
# 提交事务
cnx.commit()
cursor.close()
cnx.close()
```
2. **SQLite** (直接在Python交互式环境中):
```python
import sqlite3
conn = sqlite3.connect('your_database.db')
c = conn.cursor()
c.executemany("INSERT INTO your_table VALUES (?, ?)", data)
conn.commit() # 提交事务
conn.close()
```
3. **MongoDB** (使用Pymongo库):
```python
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['your_collection']
bulk_op = collection.initialize_unordered_bulk_op()
for record in data:
bulk_op.insert(record)
# 执行批量插入
bulk_op.execute()
```
阅读全文