python将csv导入mysql数据库
时间: 2023-09-17 20:09:13 浏览: 115
以下为Python将CSV导入MySQL数据库的示例代码:
```python
import csv
import MySQLdb
#连接MySQL数据库
db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="database_name")
cursor = db.cursor()
#打开CSV文件并读取数据
with open('data.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
#将数据插入到MySQL数据库中
cursor.execute("INSERT INTO table_name (column1, column2, column3) VALUES (%s, %s, %s)", (row['column1'], row['column2'], row['column3']))
#提交更改并关闭连接
db.commit()
cursor.close()
db.close()
```
其中,需要根据实际情况修改以下几个参数:
- host:MySQL数据库的地址
- user:MySQL数据库的用户名
- passwd:MySQL数据库的密码
- db:MySQL数据库的名称
- data.csv:需要导入的CSV文件名
- table_name:需要插入数据的MySQL表名
- column1、column2、column3:需要插入数据的MySQL表的列名
此外,还需要安装MySQLdb和csv模块,可以使用以下命令进行安装:
```python
pip install MySQL-python
pip install csv
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)