别写一段python调取mysql库代码
时间: 2024-03-11 18:40:26 浏览: 63
以下是一段Python调用MySQL库的代码,它连接到MySQL数据库,查询数据并将其写入Excel文件中:
```python
import pymysql
import xlwt
# 连接到MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='testdb')
cursor = conn.cursor()
# 查询数据
sql = "SELECT * FROM students"
cursor.execute(sql)
results = cursor.fetchall()
# 将数据写入Excel文件
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Students')
# 写入表头
header = ['ID', 'Name', 'Age', 'Gender']
for i in range(len(header)):
worksheet.write(0, i, header[i])
# 写入数据
for i in range(len(results)):
for j in range(len(results[i])):
worksheet.write(i+1, j, results[i][j])
# 保存Excel文件
workbook.save('students.xls')
# 关闭连接
cursor.close()
conn.close()
```
阅读全文