Python syntax-MySQL database (comprehensive case: read files, write to MySQL database)

Python syntax-MySQL database
Comprehensive case: read the file and write it into the MySQL database

(see the reference content at the end of the article for the project data)
insert image description here
Analysis:
insert image description here
The sql code is as follows:

create database pysql charset utf8;

use pysql;

select database();

create table orders(
	order_date date,
	order_id varchar(255),
	money int,
	province varchar(10)
);

Read data and encapsulate objects to reuse the case code in the "Object-Oriented" chapter, and modify the python file main.py to the following code:

"""
SQL 综合案例,读取文件,写入MySQL数据库中
"""

from file_define import FileReader, TextFileReader, JsonFileReader
from data_define import Record
from pymysql import Connection

text_file_reader = TextFileReader("2011年1月销售数据.txt")
json_file_reader = JsonFileReader("2011年2月销售数据JSON.txt")
jan_data: list[Record] = text_file_reader.read_data()
feb_data: list[Record] = json_file_reader.read_data()

# 将2个月份的数据合并为1个list来存储
all_data: list[Record] = jan_data + feb_data

# 构建MySQL链接对象
conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="******",
    autocommit=True
)
# 获得游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db("pysql")
# 组织SQL语句
for record in all_data:
    sql = f"insert into orders(order_date, order_id, money, province)" \
          f"values('{
      
      record.date}', '{
      
      record.order_id}',{
      
      record.money}, '{
      
      record.province}')"
    print(sql)
    # 执行SQL语句
    cursor.execute(sql)

# 关闭MySQL链接对象
conn.close()

The case results are as follows:
insert image description here

Reference content:
Reference data (https://download.csdn.net/download/qq_45833373/87895996)
The first stage of learning python basics - feel and send
dark horse programmers - python basics

Guess you like

Origin blog.csdn.net/qq_45833373/article/details/131175799