一、环境说明
MySQL版本:MySQL 8.0.40-arm64
Python版本:Python 3.13
PyMySQL版本:PyMySQL 1.1.1
请在电脑中安装以上软件并配置好开发环境。
二、Python使用MySQL的示例代码:
# 1. 导入模块
import pymysql
# 2. 连接数据库
connect = pymysql.connect(
host = 'localhost',
port = 3306,
user = 'root',
passwd = 'your passwd',
db = 'your database name',
charset = 'utf8'
)
# 3. 执行SQL语句
cursor = connect.cursor() # 获取游标
sql = "show databases;" # 获取所有数据库
cursor.execute(sql) # 执行语句
print(cursor.fetchall())
# 4. 关闭数据库
cursor.close()
connect.close()
三、PyMySQL常见类和方法
01:pymysql.connect() 属性【参数】
# 2、连接数据库
connect = pymysql.Connect(
host = 'localhost',
port = 3306,
user = 'root',
passwd = 'your passwd',
db = 'your database name',
charset = 'utf8'
)
# host MySQL服务器地址,IP地址或域名
# port MySQL服务器端口号
# user 用户名
# passwd 密码
# db 数据库名称
# charset 数据库连接编码
02:connect 对象支持的方法
# 创建游标并返回游标对象
cursor = connect.cursor()
# 提交当前事务
connect.commit()
# 回滚当前事务
connect.rollback()
# 关闭连接
connect.close()
03:cursor 对象支持的方法(执行sql语句并获得结果)
# 获取所有数据库
sql = "show databases;"
dbs = cursor.execute(sql) # 执行sql语句
print(cursor.fetchall())
# execute(op) 执行一个SQL命令
# fetchall() 获取结果集中的所有数据
# close() 关闭游标对象
# fetchone() 取得结果集的一行数据
# fetchmany(size) 获取结果集的size行数据
# rowcount 返回数据条数或影响行数
四、练习代码
01:获取数据
# 1、导入模块
import pymysql
# 2、连接数据库
connect = pymysql.connect(
host = 'localhost',
port = 3306,
user = 'root',
passwd = 'your passwd',
db = 'your database name',
charset ='utf8'
)
# 3、执行SQL语句
cursor = connect.cursor()
sql = "select * from teachers;" # 获取teachers表的数据
dbs = cursor.execute(sql)
# print(dbs)
# print(cursor.fetchone())
print(cursor.fetchall())
# 4、关闭数据库
cursor.close()
connect.close()
02:插入数据
# 1、导入模块
import pymysql
# 2、连接数据库
connect = pymysql.connect(
host = 'localhost',
port = 3306,
user = 'root',
passwd = 'your passwd',
db = 'your database name',
charset = 'utf8'
)
# 3、执行SQL语句
cursor = connect.cursor()
sql = "insert into teachers values(4,'周老师');" # 向teachers表中插入values的值
dbs = cursor.execute(sql)
# 当对表或表内数据进行插入,修改,删除时,要使用commit提交当前事务
connect.commit()
# 4、关闭数据库
cursor.close()
connect.close()