Python操作mysql

一、python连接mysql

1.python连接mysql代码示例
python 复制代码
from pymysql import Connection

# 获取到mysql数据艰苦的连接对象
conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='root'
)
# 打印mysql数据库软件信息
print(conn.get_server_info())
# 关闭到数据库的连接
conn.close()
2.python执行sql语句
(1)非查询语句
python 复制代码
from pymysql import Connection

# 获取到mysql数据艰苦的连接对象
conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='root'
)
# 获取游标对象
cursor = conn.cursor()
# 选择要操作的数据库
conn.select_db("test")
# 使用游标对象,执行sql语句
cursor.execute("create table test_py_table(id int, info varchar(255))")
# 关闭到数据库的连接
conn.close()
(2)查询语句
python 复制代码
from pymysql import Connection

# 获取到mysql数据艰苦的连接对象
conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='root'
)
# 获取游标对象
cursor = conn.cursor()
# 选择要操作的数据库
conn.select_db("test")
# 使用游标对象,执行sql语句
cursor.execute("select * from test_py_table")
# 获取查询结果(这里是类型注释,已经知道结果集是元祖)
results: tuple = cursor.fetchall()
for row in results:
    print(row)
# 关闭到数据库的连接
conn.close()
(3)数据插入、变更

可以通过conn的提交方法,也可以通过如下设置自动提交

python 复制代码
from pymysql import Connection

# 获取到mysql数据艰苦的连接对象
conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='root'
)
# 获取游标对象
cursor = conn.cursor()
# 选择要操作的数据库
conn.select_db("test")
# 使用游标对象,执行sql语句
cursor.execute("insert into test_py_table values(3,333)")
# commit确认提交
conn.commit()
# 关闭到数据库的连接
conn.close()
相关推荐
星越华夏3 分钟前
python中四种获取文件后缀名的方法
开发语言·python
lunzi_08263 分钟前
【学习笔记】《Python编程 从入门到实践》第9章:类、继承、组合与面向对象编程
笔记·python·学习
大蚂蚁2号5 分钟前
本地批量音视频转文本免费工具
python·音视频·开源软件
copyer_xyf10 分钟前
FastAPI 项目骨架搭建
前端·后端·python
十正11 分钟前
aiohttp.TCPConnector 连接池原理详解
网络·python·tcp·aiohttp
LoserChaser15 分钟前
Flask 文件上传服务器 - 知识点总结
服务器·python·flask
cd9888017 分钟前
2026年,哪家电销机器人定制更灵活?
python
二十七剑18 分钟前
LangGraph 源码深度解析:_branch.py 条件分支底层实现原理
python
javajenius20 分钟前
Pixi:用 Rust 重写 Conda 体验的包管理工具
开发语言·其他·rust·conda
神明不懂浪漫21 分钟前
【第二章】Java中的数据类型,运算符与程序逻辑控制
java·开发语言·经验分享·笔记