sqlite插入多条数据
时间: 2023-08-11 12:03:39 浏览: 186
要在SQLite中插入多条数据,可以使用多个INSERT语句或者使用单个INSERT语句插入多个值。下面是两种方法的示例:
方法一:使用多个INSERT语句
```python
import sqlite3
# 连接到数据库
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
# 定义插入语句
insert_query = "INSERT INTO table_name (column1, column2) VALUES (?, ?)"
# 定义要插入的数据
data = [
('value1', 'value2'),
('value3', 'value4'),
('value5', 'value6')
]
# 执行多个插入操作
cursor.executemany(insert_query, data)
# 提交更改
conn.commit()
# 关闭连接
conn.close()
```
方法二:使用单个INSERT语句插入多个值
```python
import sqlite3
# 连接到数据库
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
# 定义插入语句
insert_query = "INSERT INTO table_name (column1, column2) VALUES (?, ?)"
# 定义要插入的数据
data = [
('value1', 'value2'),
('value3', 'value4'),
('value5', 'value6')
]
# 构建参数字符串
params = ', '.join(['(?, ?)'] * len(data))
# 构建完整的SQL语句
insert_query = insert_query + ' VALUES ' + params
# 执行插入操作
cursor.execute(insert_query, [item for sublist in data for item in sublist])
# 提交更改
conn.commit()
# 关闭连接
conn.close()
```
以上是使用Python的示例代码,你需要将`table_name`替换为你要插入数据的表名,`column1`和`column2`替换为你要插入的列名,以及`data`替换为你要插入的实际数据。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)