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()
相关推荐
一隅论数智16 小时前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙16 小时前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!16 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
rockmelodies16 小时前
# Windows Server2008 R2 Standard(SP1镜像U盘)重置本地管理员密码【完整详细步骤】
windows·密码破解
XiHongShi201616 小时前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
qq_4260039616 小时前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫16 小时前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技17 小时前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
爱吃苹果的日记本17 小时前
离散数学第六课
学习·离散数学