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()
相关推荐
阿尔的代码屋4 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
于眠牧北4 小时前
MySQL的锁类型,表锁,行锁,MVCC中所使用的临键锁
mysql
AI探索者21 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者21 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python