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()
相关推荐
cjl_8520082 分钟前
[MySQL] MySQL复合查询(多表查询、子查询)
android·mysql·adb
XP62265 分钟前
MySQL单表存多大的数据量比较合适
数据库·mysql
~央千澈~12 分钟前
抖音弹幕游戏开发之第9集:pyautogui进阶 - 模拟鼠标操作·优雅草云桧·卓伊凡
开发语言·python·游戏
啊阿狸不会拉杆16 分钟前
《机器学习导论》第 19 章 - 机器学习实验的设计与分析
人工智能·python·算法·决策树·机器学习·统计检验·评估方法
是店小二呀17 分钟前
MySQL 核心操作:表的CRUD、聚合与分组深度实践
数据库·mysql
遇见你的雩风21 分钟前
【Golang】--- Goroutine
开发语言·golang
v沙加v23 分钟前
Java Rendering Engine Unknown
java·开发语言
张3蜂24 分钟前
python知识点点亮
开发语言·python
好学且牛逼的马24 分钟前
【Hot100|26-LeetCode 21. 合并两个有序链表 - 完整解法详解】
开发语言·python
Katecat9966325 分钟前
矿井地雷检测与识别:Yolo11-HAFB-1模型应用详解
python