一、下载第三方包pymysql
pip install pymysql
二、python代码
"""
演示python pymysql库的基本操作
"""
# 构建到mysql数据库的链接
from pymysql import Connection
# 创建对象实例 Connection是个类 关键字传参
conn = Connection(
host = "localhost", # 主机名
port = 3306, # 端口号
user = "root", # 账户名
passwd = "root", # 密码
)
# -------- 执行非查询性质sql --------
# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('my_data_base')
# 执行sql
# cursor.execute('create table py_student(id int, info varchar(255))')
# -------- 执行查询性质sql --------
cursor.execute('select * from student')
result: tuple = cursor.fetchall() # 获取全部数据fetch all
for r in result:
print(r)
"""
运行结果:
(2, '周杰伦', 22, '女')
(3, '王五', 24, '男')
(4, '张三1', 25, '男')
(5, '李四2', 26, '女')
(6, '王五3', 27, '男')
"""
# 返回服务器的版本号
print(conn.get_server_info())
# 5.7.26
# 关闭链接
conn.close()
三、相关截图
3.1 python执行结果图
image.png
3.2 数据库执行结果图
image.png
image.png