Day14-Python基础学习之pymysql

复制代码
安装:pip install pymysql

# python操作Mysql数据库

from pymysql import Connection

# 构建数据库链接
conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='123456',
    autocommit=True  # 这里开启自动提交,就无需手动确认了
)
print(conn.get_server_info())

cursor = conn.cursor()  # 获得游标对象
conn.select_db("test")
# 执行sql
cursor.execute("create table test_pymysql(id int);")
cursor.execute("select * from student;")
results = cursor.fetchall()
for r in results:  # 这是元组
    print(r)
# 注意在执行插入语句或发生数据更改语句时,默认需要提交更改
cursor.execute("insert into test_pymysql values(10001);")
conn.commit()   # 这里确认了

# 关闭链接
conn.close()



# 综合案例
from 数据分析案例.file_define import FileReader, TextFileReader, JsonFileReader
from 数据分析案例.data_define import Record

text_file_reader = TextFileReader("D:/BaiduNetdiskDownload/第13章资料/2011年1月销售数据.txt")
json_file_reader = JsonFileReader("D:/BaiduNetdiskDownload/第13章资料/2011年2月销售数据JSON.txt")

# 获取月份数据
jan_data: list[Record] = text_file_reader.read_data()
feb_data: list[Record] = json_file_reader.read_data()
# 将两个月份的数据合成一个list
all_data: list[Record] = jan_data + feb_data

# 开始操作
conn1 = Connection(host='localhost', port=3306, user='root', password='123456', autocommit=True)
cursor1 = conn1.cursor()
conn1.select_db("py_sql")
for record in all_data:
    sql = ("insert into orders(order_date, order_id, money, province) values('{record.date}','{record.order_id}','{record.money}',"
           "'{record.province}')")
    print(sql)
    cursor1.execute(sql)

conn1.close()
相关推荐
wuyk55533 分钟前
Python办公自动化-第01讲-环境搭建与自动化认知
python·自动化·pyqt
高洁011 小时前
数字孪生与计算机视觉:让机器看懂现场
人工智能·python·机器学习·transformer·迁移学习
ComPDFKit1 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
yz_aiks3 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
2601_967980115 小时前
Flask Web 应用
python·flask·web开发·环境变量·虚拟环境
aifannihao5 小时前
ß 大写变 SS:用 Python 算清 Ruby2Shell 的缓冲区账本
python·安全·标准库·缓冲区溢出·字符串编码
liwulin05065 小时前
【OLLAMA】调用SKILL的通用ReAct
python
郝学胜-神的一滴6 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
Norna7 小时前
Git 给路径加了引号,这个文件就从 review 里消失了
python