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()
相关推荐
Trouvaille ~10 分钟前
【MySQL】视图:虚拟表的妙用
数据库·mysql·adb·面试·数据处理·后端开发·视图
m0_7478545229 分钟前
如何为禁用按钮点击添加提示文案
jvm·数据库·python
朝阳58137 分钟前
rust 交叉编译指南
开发语言·后端·rust
2301_8035389541 分钟前
CSS如何设计简洁的移动端底部固定导航_利用position-fixed实现
jvm·数据库·python
vegetablec1 小时前
CSS如何制作卡片翻开呈现另一面的翻牌动画
jvm·数据库·python
吕源林1 小时前
Golang怎么Redis发布订阅_Golang如何用Publish和Subscribe收发消息【实战】
jvm·数据库·python
用户8356290780511 小时前
使用 Python 合并与拆分 Excel 单元格的实用方法
后端·python
2301_764150561 小时前
Golang colly爬虫框架如何用_Golang colly教程【进阶】
jvm·数据库·python
2301_803538951 小时前
SQL统计各分组中排名前三的记录_使用窗口函数RANK
jvm·数据库·python
2301_782659181 小时前
如何让按钮悬停时阴影位置保持固定(仅按钮位移)
jvm·数据库·python