python mysql excel 脚本
时间: 2024-04-28 21:16:09 浏览: 108
Python可以通过MySQL Connector库来连接MySQL数据库,并使用pandas库来读写Excel文件。下面是一个简单的Python脚本示例,用于连接MySQL数据库并将查询结果导出到Excel文件中:
```python
import mysql.connector
import pandas as pd
# 连接MySQL数据库
cn = mysql.connector.connect='your_username', password='your_password',
host='your_host', database='your_database')
执行SQL查询
cursor = cnx.cursor()
query = "SELECT * your_table"
cursor.execute(query)
# 获取查询结果
results = cursor.fetchall()
# 将结果转换为DataFrame
df = pd.DataFrame(results, columns=cursor.column_names)
# 将DataFrame写入Excel文件
df.to_excel('output.xlsx', index=False)
# 关闭数据库连接
cursor.close()
cnx.close()
```
请注意,你需要将`your_username`、`your_password`、`your_host`、`your_database`和`your_table`替换为你自己的数据库信息。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)