Software Testing | Detailed Guide to Accessing MySQL Database Using PyMySQL

Introduction

PyMySQL is a popular MySQL database driver in Python, which provides convenient methods to connect, query and update MySQL databases. This article will provide you with a detailed guide to using PyMySQL to access MySQL database, including installing PyMySQL, connecting to the database, performing query and update operations, etc.

Environmental preparation

Before you begin, you need to make sure you have the PyMySQL library installed. It can be installed using the pip command:

pip install pymysql

Connect to database

First you need to establish a connection to the MySQL database. Sample code using the PyMySQL library is as follows:

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

Call connect the method to generate an connect object, and access the database through this object

connectMain parameters of the method

  • user, the user who accesses the database
  • password, the password to access the database
  • host, the host where the Mysql database service is located
  • port, the port number of the Mysql database service, the default value is 3306
  • db,Database name
  • charset,Character Encoding

connect object

  • connect() After successfully connecting to the database using the method, connect() the method returns an connect()object
  • When communicating with the database, connect SQL query commands are sent to the object, and connectthe object receives SQL query results.

Common methods

  • close(), close the database connection
  • commit(), commit the current transaction
  • rollback(), cancel the current transaction
  • cursor(), create a cursor object for executing SQL query commands

cursor object

The cursor object is used to execute SQL commands and obtain SQL query results.

Common methods

  • close(), close the cursor object
  • execute(), execute a database query or command
  • fetchone(), returns the next row of the result set
  • fetchall(), returns all rows in the result set

Create database

We create a studentslibrary named and a studentstable named, containing idthree fields. The code is as follows name:age

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()

Query data

Before querying data, we must first connect to the database. Once the database connection is established, various query operations can be performed.

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

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

fetchall match

Return all matching results

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)

fetchonematch

Return a record

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

rows = cursor.execute(sql)

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


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

fetchmanymatch

How many records to return can be customized

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

rows = cursor.execute(sql)

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

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


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

Insert data

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

change the data

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

delete data

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

Summarize

This article provides detailed steps for using the PyMySQLaction MySQLdatabase. Starting from installation PyMySQL, connecting to the database, executing queries and adding, modifying and deleting operations, these are the key steps required to access the MySQL database using PyMySQL. I hope this article can help you easily operate MySQL database using PyMySQL and achieve your data storage and retrieval needs.

Finally, I would like to thank everyone who reads my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can take it directly:

This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!

Guess you like

Origin blog.csdn.net/2301_78276982/article/details/135427213