安装: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()
Day14-Python基础学习之pymysql
学编程的小白462024-04-17 17:03
相关推荐
程序员龙叔8 小时前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL用户83562907805111 小时前
使用 Python 操作 Word 内容控件通信小呆呆11 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?H__Rick11 小时前
自动对焦学习-3Daisy Lee11 小时前
量化学习-第1章-什么是量化金融qq_3692243311 小时前
Windows全系通用!ntdll.dll文件丢失、报错、闪退问题的完整排查与修复教程Alsn8612 小时前
等待学习-学习目录:Docker 容器安全攻防码云骑士12 小时前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则YM52e12 小时前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本