0
点赞
收藏
分享

微信扫一扫

Python 连接 MySQL


PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装

# 安装 PyMySQL
pip install PyMySQL

1、连接数据库

import pymysql

# 打开数据库连接
db=pymysql.connect("192.168.1.113","root","Abc@123456","school")

# 使用 cursor 方法获取操作游标
cursor=db.cursor()

2、查询 单条记录

# 查询操作 单条记录
sql="select * from student where name='alice'"
cursor.execute(sql)

row=cursor.fetchone()
print(row)

3、查询 多条记录

# 查询操作 多条记录
sql="select * from student"
cursor.execute(sql)
rows=cursor.fetchall()

for val in rows:
print(val)

4、更新数据

# 更新操作 name 是变量
sql="update student set area='10:00' where name='%s'" %name
cursor.execute(sql)

# 执行操作
db.commit()

4、关闭连接

# 关闭数据库连接
db.close()

举报

相关推荐

0 条评论