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()


相关推荐
孟健12 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞13 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
倔强的石头_14 小时前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
曲幽16 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程20 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪20 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook21 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img