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()
相关推荐
车载测试工程师6 分钟前
CAPL学习-SOME/IP交互层-TCP处理类函数
学习·tcp/ip·以太网·capl·canoe
Dxy123931021610 分钟前
Python的正则表达式入门:从小白到能手
服务器·python·正则表达式
艾上编程17 分钟前
第三章——爬虫工具场景之Python爬虫实战:行业资讯爬取与存储,抢占信息先机
开发语言·爬虫·python
Pyeako18 分钟前
网络爬虫相关操作--selenium库(超详细版)
爬虫·python·selenium
dagouaofei21 分钟前
全面整理6款文档生成PPT工具,PDF转PPT不再难
python·pdf·powerpoint
β添砖java25 分钟前
python第一阶段第10章
开发语言·python
2301_8059629328 分钟前
Windows连接腾讯云服务器
服务器·windows·腾讯云
YJlio37 分钟前
ZoomIt 学习笔记(11.7):安装与基础使用——演示/授课/录屏的神级放大镜
笔记·学习·intellij-idea
伊玛目的门徒44 分钟前
HTTP SSE 流式响应处理:调用腾讯 智能应用开发平台ADP智能体的 API
python·网络协议·http·腾讯智能体·adp·智能应用开发平台
倔强的小石头_1 小时前
Python 从入门到实战(八):类(面向对象的 “对象模板”)
服务器·开发语言·python