写一个函数,传入一个表名,将表中所有数据导出到一个 Excel 中。
我们先捋捋这个代码的过程:
- 先链接数据库
- 通过函数传入的表名,执行 sql 语句读取表中所有数据
- 将 sql 执行结果赋值,然后关闭游标和数据库的链接
- 实例化一个 Excel 对象,并激活
- 将执行 sql 得到的结果写入 Excel 中
- 保存 Excel
import pymysql
import openpyxl
# 下边链接信息为虚拟的,大家只要对号入座填写自己的数据库连接信息即可
host = "127.127.127.127”
username = "Mac"
passwd = "123456"
db = "Mac"
port = 3306
charset = "utf8"
excel_name = "students.xlsx"
def wr_Excel(table_name):
# 连数据库,读取数据
conn = pymysql.connect(host=host, user=username,
passwd=passwd, db=db,
port=port, charset=charset)
cur = conn.cursor()
sql = "select * from %s;" % table_name
cur.execute(sql)
# 使用 %s 占位符可以占位 where 条件,但是不能占位表名
# 实际为了防止 sql 注入,在where 条件使用占位符时通常使用下述方法
# sql = "select * from table_name where %s;" (此时假如要输入的变量为 age)
# cur.execute(sql, age)
sql_result = cur.fetchall()
cur.close()
conn.close()
# 写 Excel
book = openpyxl.Workbook()
sheet = book.active
fff = [filed[0] for filed in cur.description] # 获取表头信息
sheet.append(fff)
for i in sql_result:
sheet.append(i)
book.save("%s" % excel_name)
wr_Excel('faker_user')