Python学习笔记(13) --Mysql,Python关联数据库

传送门==>B站黑马python入门教程


目录


Mysql之前在学习Java时已完成学习

mysql学习记录


Python关联数据库

基础案例

pymysql

处理使用图形化工具之外,也可以使用编程语言执行SQL操作数据库,

在Python中,可使用pymysql完成对mysql数据库的操作

pip install pymysql

创建到mysql的数据库链接

python 复制代码
from pymysql import Connection

# 创建链接
conn = Connection(host="localhost",port=3306,user="root",password="123456",
                  database="python_study",charset="utf8")

# 链接数据库版本信息;
print (conn.get_server_info())

# 关闭
conn.close()

案例:测试非查询类型的SQL语句

powershell 复制代码
from pymysql import Connection

# 创建链接
conn = Connection(host="localhost",port=3306,user="root",password="123456",
                  database="python_study",charset="utf8")

# 链接数据库版本信息;
print (conn.get_server_info())

#获取游标对象
cursor = conn.cursor()
# 创建数据表
sql = "CREATE TABLE test_pymysql(id INT , info VARCHAR(255))"
cursor.execute(sql)

# 关闭
conn.close()

在数据库客户端查看,数据表已创建

案例:测试查询类型的SQL语句

python 复制代码
from pymysql import Connection

# 创建链接
conn = Connection(host="localhost",port=3306,user="root",password="123456",
                  database="python_study",charset="utf8")

# 链接数据库版本信息;
print (conn.get_server_info())

#获取游标对象
cursor = conn.cursor()
# 创建数据表
sql = "select * from test_pymysql"
cursor.execute(sql)

# 获取结果
results : tuple = cursor.fetchall()
for result in results:
    print(result)

# 关闭
conn.close()

案例:链接数据库且插入数据

python 复制代码
from pymysql import Connection

# 创建链接
conn = Connection(host="localhost",port=3306,user="root",password="123456",
                  database="python_study",charset="utf8")

#获取游标对象
cursor = conn.cursor()
# 创建数据表
sql = "insert into test_pymysql values(3,'Q3')"
cursor.execute(sql)

# 提交
conn.commit()
# 关闭
conn.close()

若在链接参数中指定autocommit=True 自动提交开启,

则不用在代码中执行 commit手动提交


综合案例


创建数据库

sql 复制代码
create table orders(
	order_date DATE,
	order_id VARCHAR(255),
	money INT,
	province VARCHAR(10)
)
python 复制代码
from file_define import TextFileReader, JsonFileReader
from data_define import Record
from pymysql import Connection

text_file_reader = TextFileReader("F:/pythonworkspace/startDemo/fileDemopath/2011年1月销售数据.txt")
json_file_reader = JsonFileReader("F:/pythonworkspace/startDemo/fileDemopath/2011年2月销售数据JSON.txt")

jan_data: list[Record] = text_file_reader.read_data()
feb_data: list[Record] = json_file_reader.read_data()
# 将2个月份的数据合并
all_data: list[Record] = jan_data + feb_data

# 构建MySQL链接对象
conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="123456",
    database="python_study",
    autocommit=True
)
# 获得游标对象
cursor = conn.cursor()
# 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}')"
    # 执行SQL语句
    cursor.execute(sql)

# 关闭链接
conn.close()


相关推荐
荣码5 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵16 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li18 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
jiayou641 天前
KingbaseES 表级与列级加密完全指南
数据库·后端
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
GBASE2 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化