软件测试|使用PyMySQL访问MySQL数据库的详细指南

在这里插入图片描述

简介

PyMySQL是Python中流行的MySQL数据库驱动程序,它提供了便捷的方法来连接、查询和更新MySQL数据库。本文将为您提供使用PyMySQL访问MySQL数据库的详细指南,包括安装PyMySQL、连接数据库、执行查询和更新操作等。

获取更多技术资料,请点击!

环境准备

在开始之前,您需要确保已经安装了PyMySQL库。可以使用pip命令进行安装:

pip install pymysql

连接到数据库

首先需要建立与MySQL数据库的连接。使用PyMySQL库的示例代码如下:

pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    password = '123456',
    db ='students',
    charset = 'utf8'
)

调用connect 方法生成一个 connect 对象, 通过这个对象来访问数据库

connect 方法的主要参数

  • user,访问数据库的用户
  • password,访问数据库的密码
  • host,Mysql 数据库服务所在的主机
  • port,Mysql 数据库服务的端口号,默认值为 3306
  • db,数据库名
  • charset,字符编码

connect 对象

  • 使用 connect() 方法与数据库连接成功后,connect() 方法返回一个 connect() 对象
  • 与数据库进行通信时, 向 connect 对象发送 SQL 查询命令, 并 connect 对象接收 SQL 查询结果

常用方法

  • close(), 关闭数据库连接
  • commit(),提交当前事务
  • rollback(),取消当前事务
  • cursor(),创建一个游标对象用于执行 SQL 查询命令

cursor 对象

cursor 对象用于执行 SQL 命令和得到 SQL 查询结果

常用方法

  • close(),关闭游标对象
  • execute(),执行一个数据库查询或命令
  • fetchone(),返回结果集的下一行
  • fetchall(),返回结果集中所有行

创建数据库

我们创建一个名为students的库,并创建一个名为students的表,包含idnameage三个字段,代码如下:

db = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='1234567890',
    db='students',
    charset='utf8'
)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

sql = """SET character_set_database=utf8;
SET character_set_server=utf8;
DROP DATABASE IF EXISTS students;
CREATE DATABASE students;
USE school;"""
lists = sql.split("\n")
for i in lists:
    cursor.execute(i)

create_sql = """
CREATE TABLE students(
    id VARCHAR(32),
    name VARCHAR(32),
    age INT
);
"""
cursor.execute(create_sql)
insert_sql = """
INSERT INTO students(id, name, age) VALUES ('202301', '穆勒', '18');
"""
cursor.execute(insert_sql)
db.commit()
db.close()

查询数据

查询数据之前,我们先要与数据库进行连接,一旦建立了数据库连接,就可以执行各种查询操作。

db = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='1234567890',
    db='students',
    charset='utf8'
)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

fetchall匹配

返回全部匹配结果

sql = "select * from students;"

rows = cursor.execute(sql)

# 记录数
print("there are %d students" % rows)

# 可迭代对象
students = cursor.fetchall()
# 循环输出
for i in students:
    print(i)


# 输出结果
there are 1 students
('202301', '穆勒', 18)

fetchone匹配

返回一条记录

# 查询数据 - fetchone
sql = "select * from students;"

rows = cursor.execute(sql)

# 根据记录数循环
for i in range(rows):
    student = cursor.fetchone()
    print(student)


# 输出结果
('202301', '穆勒', 18)

fetchmany匹配

可以自定义返回多少条记录数

# 查询数据 - fetchmany
sql = "select * from students;"

rows = cursor.execute(sql)

# 可迭代对象
students = cursor.fetchmany(3)

# 循环结果集
for i in students:
    print(i)


# 输出结果
('202301', '穆勒', 18)

插入数据

db = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='1234567890',
    db='students',
    charset='utf8'
)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 增加数据
id = 202302
name = "基米希"
age = 24

sql = 'insert into students(id,name,age) VALUES("%s", "%s", %d)' % (id, name, age)

# 执行 insert sql
rows = cursor.execute(sql)

# 查看 insert 语句返回结果,其实就是执行成功了多少条数据
print('Insert %d students' % rows)

# 只有调用了 commit 方法才能将数据落盘,即提交 insert 操作
db.commit()


# 输出结果
Insert 1 students

修改数据

db = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='1234567890',
    db='students',
    charset='utf8'
)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 更新数据
id = 202302
name = "基米希"
age = 16

sql = 'UPDATE students SET name="%s", age=%d WHERE sno="%s"' % (name, age, id)

# 执行 update sql
rows = cursor.execute(sql)

# 返回成功修改记录的条数
print('update %d students' % rows)

# 调用 commit,才会将 update 操作提交
db.commit()


# 输出结果
update 1 students

删除数据

db = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='1234567890',
    db='students',
    charset='utf8'
)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 更新数据
sno = 202302
name = "小菠萝"
age = 14

sql = 'DELETE FROM students'

# 执行 delete sql
rows = cursor.execute(sql)

# 返回成功修改记录的条数
print('delete %d students' % rows)

# 调用 commit,才会将 delete 操作提交
db.commit()


# 输出结果
delete 2 students

总结

本文介绍了使用PyMySQL操作MySQL数据库的详细步骤。从安装PyMySQL开始,连接数据库,执行查询和增加修改删除操作,这些都是使用PyMySQL访问MySQL数据库所需的关键步骤。希望本文能够帮助您使用PyMySQL轻松地操作MySQL数据库,并实现您的数据存储和检索需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值