Python connects to the Mysql database and reads data from the Mysql database and stores it in an excel file

0. Environmental preparation and introduction

  • Operating System: Windows10
  • Python version: Python 3.7.2
  • Tool: Pycharm Professional Edition
  • Rely on third-party libraries:
    • pymysql (connect to database)
    • openpyxl (operate excel sheet)

1. Python connect to MySQL database

The following code is the basic code for connecting to the database. The code implements the query of all tables in the current database. For the specific meaning of each line of code, please read the comments behind the code in detail
import pymysql
# 连接数据库
conn = pymysql.connect(host="localhost", user="root", passwd="你的数据库密码",
                       db="mystore", port=3306,charset="utf8")
cur = conn.cursor()  # 创建游标对象

cur.execute("show tables;")    # 使用execute()方法执行SQL代码
table_names=cur.fetchall() # 返回执行SQL代码后的结果集,默认为元组
#打印
print(table_names)

cur.close()
conn.close()  # 关闭数据库连接
The following is a screenshot of the code execution:

Insert picture description here

Python control excel sheet

How to use the specific openpyxl library, I have sorted out the bloggers that the editor thinks are better, and pasted their article links here.
Detailed explanation of how to use python openpyxl (recommended ♥)
openpyxl official manual-English version of
openpyxl official manual-简书

"""
    操作ceshi.xlsx,从A1-J1单元格中写入hello
"""
import openpyxl

wb = openpyxl.load_workbook('ceshi.xlsx')  # 创建一个工作簿
ws = wb.active  # 选择默认的sheet

# 从A1-J1单元格中写入hello
for i in range(65,65+10):
    ws[chr(i)+'1'] = 'hello'

wb.save('ceshi.xlsx')

Code execution result

Insert picture description here

Python connects to the Mysql database and reads data from the Mysql database and stores it in an excel file

Query in the database

Insert picture description here
Insert picture description here

code show as below:
import openpyxl
import pymysql


# 连接数据库
conn = pymysql.connect(host="localhost", user="root", passwd="你的数据库密码",
                       db="数据库名", port=3306, charset="utf8")
cur = conn.cursor()

wb = openpyxl.load_workbook('ceshi.xlsx')  # 打开文件
ws = wb.active

"""  获取表结构,并将表头写入excel """
cur.execute("desc product;")
table_head = cur.fetchall()
li = []
for d in table_head:
    li.append(d[0])
li.reverse()
i = 65
while li:
    ws[chr(i)+'1'] = li.pop()
    i = i+1

""" 获取表中所有数据,并写入excel """
cur.execute("select * from product;")
table_product_data = cur.fetchall()
j = 1
for da in table_product_data:
    di = 65
    j = j + 1
    for k in range(len(da)):

        ws[chr(di) + str(j)] = da[k]
        di = di+1

wb.save('ceshi.xlsx')

cur.close()
conn.close()
Code execution result

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_37955704/article/details/103831982