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()
相关推荐
zh路西法几秒前
【宇树机器人强化学习】(七):复杂地形的生成与训练
python·深度学习·机器学习·机器人
python猿5 分钟前
打卡Python王者归来--第30天
开发语言·python
qq_334903156 分钟前
嵌入式C++驱动开发
开发语言·c++·算法
阿贵---17 分钟前
C++代码规范化工具
开发语言·c++·算法
2401_8318249620 分钟前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
2401_8796938722 分钟前
用Pygame开发你的第一个小游戏
jvm·数据库·python
暮冬-  Gentle°25 分钟前
自定义内存检测工具
开发语言·c++·算法
一直都在57225 分钟前
Java死锁
java·开发语言
娇娇yyyyyy28 分钟前
QT编程(15): Qt 按键事件和定时器事件
开发语言·qt
用户03321266636729 分钟前
使用 Python 查找并高亮 Word 文档中的文本
python