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()
相关推荐
ZhengEnCi41 分钟前
08c. 检索算法与策略-混合检索
后端·python·算法
Hoffer_5 小时前
MySQL 强制索引:USE/FORCE INDEX 用法与避坑
后端·mysql
Hoffer_5 小时前
MySQL 索引核心操作:CREATE/DROP/SHOW
后端·mysql
明月_清风6 小时前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风7 小时前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly21 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling1 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook1 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风1 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风1 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python