Python 구문-MySQL 데이터베이스
포괄적인 경우: 파일을 읽고 MySQL 데이터베이스에 씁니다
(프로젝트 데이터는 문서 끝에 있는 참조 내용 참조)
분석:
SQL 코드는 다음과 같습니다.
create database pysql charset utf8;
use pysql;
select database();
create table orders(
order_date date,
order_id varchar(255),
money int,
province varchar(10)
);
데이터를 읽고 개체를 캡슐화하여 "객체 지향" 장의 사례 코드를 재사용하고 파이썬 파일 main.py를 다음 코드로 수정합니다.
"""
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()
케이스 결과는 다음과 같습니다.
참고내용 :
참고자료 (https://download.csdn.net/download/qq_45833373/87895996)
파이썬 기초 학습의 첫 단계 - 느끼고 보내다
다크호스 프로그래머 - 파이썬 기초