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()
相关推荐
想睡hhh1 天前
mysql表的操作——mysql表的约束
数据库·mysql
m0”-“0m1 天前
MySQL、Nignx和Docker在Linux上的安装详解
linux·数据库·mysql
嫂子的姐夫1 天前
11-py调用js
javascript·爬虫·python·网络爬虫·爬山算法
程序员莫小特1 天前
老题新解|计算2的N次方
开发语言·数据结构·算法·青少年编程·信息学奥赛一本通
图亚Vanta1 天前
Python入门第一课:Python安装、VSCode/Pycharm配置
vscode·python·pycharm
睿思达DBA_WGX1 天前
使用 python-docx 库操作 word 文档(2):在word文档中插入各种内容
python·word
武子康1 天前
Java-145 深入浅出 MongoDB 基本操作详解:数据库查看、切换、创建集合与删除完整教程
java·数据库·sql·mysql·mongodb·性能优化·系统架构
white-persist1 天前
XXE 注入漏洞全解析:从原理到实战
开发语言·前端·网络·安全·web安全·网络安全·信息可视化
刘大猫.1 天前
mysql数据库压缩
数据库·mysql·压缩·mysql数据库压缩·数据库压缩·数据库备份与压缩
会飞的架狗师1 天前
【MySQL体系】第4篇:MySQL 查询优化实用技巧
数据库·mysql