写一个函数,传入一个表名,将表中所有数据导出到一个 Excel 中。

我们先捋捋这个代码的过程:

  1. 先链接数据库
  2. 通过函数传入的表名,执行 sql 语句读取表中所有数据
  3. 将 sql 执行结果赋值,然后关闭游标和数据库的链接
  4. 实例化一个 Excel 对象,并激活
  5. 将执行 sql 得到的结果写入 Excel 中
  6. 保存 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')

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐