python-pymysql连接本地数据库

一、下载第三方包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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。