Detailed explanation of the pymysql module in Python: common operations such as installation, connection, and execution of SQL statements


Preface

  In Python, we often need to connect and operate databases. pymysql is a popular Python module designed for interacting with MySQL databases. This article will introduce the basic usage of the pymysql module and some of its application scenarios in actual development.


1. Introduction to pymysql module

  pymysql is a third-party module for Python programming that is used to connect and operate MySQL databases. It provides a simple and powerful interface that enables developers to easily perform various database operations in Python programs, such as querying, inserting, updating and deleting data, etc.

  The pymysql module is implemented by Python, which follows the Python Database API specification (PEP 249), which makes it compatible with other database APIs and makes it easier to switch between different databases.

  pymysql is very popular in the Python developer community because it is easy to use, powerful, and has good performance. It provides many advanced features, such as transaction management, connection pool, data type conversion, etc., making the development of database-driven applications more convenient and efficient.

  In summary, the pymysql module is an important tool that helps Python developers easily interact and operate with MySQL databases.


2. Usage steps

1. Install the pymysql module

Before using the pymysql module, you first need to install it into your Python environment. The pymysql module can be installed by running the following command on the command line:

pip install pymysql

If ['pip' is not recognized as an internal or external command, operable program or batch file. 】You can check my other article to solve it!

[Three-step solution] 'pip' is not recognized as an internal or external command, operable program or batch file.

2. Connect to database and common operations

The code is as follows (example):

# 导入pymysql模块
import pymysql

# 建立数据库连接
conn = pymysql.connect(
    host='localhost',		# 主机名(或IP地址)
    port=3306,				# 端口号,默认为3306
    user='root',			# 用户名
    password='password',	# 密码
    charset='utf8mb4'  		# 设置字符编码
)

# 获取mysql服务信息(测试连接,会输出MySQL版本号)
print(conn.get_server_info())

# 创建游标对象
cursor = conn.cursor()

# 选择数据库
conn.select_db("mytable")

# 执行查询操作
cursor.execute('SELECT * FROM mytable')

# 获取查询结果,返回元组
result : tuple = cursor.fetchall()

# 关闭游标和连接
cursor.close()
conn.close()

  In this example, we use the connect() function in pymysql to establish a connection with the MySQL database, and we need to provide the host address, port number, user name, and password of the database. Additionally we can set the character encoding to ensure correct handling of special characters in the data.

3. Execute SQL statements

  Once the connection to the database is established, we can perform various SQL operations such as inserts, updates, deletes, and queries. Here are some examples of common SQL operations:

Insert data

sql = "INSERT INTO mytable (name, age) VALUES ('John', 25)"
cursor.execute(sql)
conn.commit()

update data

sql = "UPDATE mytable SET age = 26 WHERE name = 'John'"
cursor.execute(sql)
conn.commit()

delete data

sql = "DELETE FROM mytable WHERE name = 'John'"
cursor.execute(sql)
conn.commit()

Query data

sql = "SELECT * FROM mytable"
cursor.execute(sql)
# 只要不涉及数据的更改,可以不需要调用commit()方法提交更改
result = cursor.fetchall()
for row in result:
    print(row)

  Use the cursor.execute() method to execute the SQL statement. When changing the data in the table, you must call the conn.commit() method to commit the change, otherwise the data in the database table will not change. After the operation is completed, the query results can be obtained using the cursor.fetchall() method, which returns a tuple.

If you think the commit() method is a bit cumbersome, you can set autocommit = True when creating a connection to automatically submit changes, so that you don't need to call the commit() method after each SQL operation. The sample code is as follows:

# 获取mysql连接对象
conn = pymysql.Connect(
    host="localhost",       # 主机名(或IP地址)
    port=3306,              # 端口号,mysql默认3306
    user='root',            # 用户名
    password='password',    # 密码
    autocommit=True         # 自动提交更改
)

4.Error handling

  When operating the database, you may encounter various errors. Both Python and pymysql provide us with some methods to help handle errors, such as using try-except blocks to catch exceptions, and using the conn.rollback() method to roll back transactions.

try:
    # 执行一些操作
    ...
    conn.commit()
except Exception as e:
    print(f"发生错误:{
      
      e}")
    conn.rollback()
finally:
    cursor.close()
    conn.close()

  In this example, the operations in the try block may throw an exception. We can catch the exception in the except code block and handle the error by printing the error message. In addition, you should use the finally code block to close the cursor and connection regardless of whether an exception occurs.


Summarize

  This article introduces the basic use of the pymysql module in Python. By using the pymysql module, we can easily connect, operate and manage MySQL databases. Whether it is a simple query or complex transaction processing, pymysql provides us with powerful and flexible functions.

  I hope this article can help you get started quickly and master the use of the pymysql module! If you want to learn more about pymysql, it is recommended to refer to the official documentation or other related resources.

pymysql official documentation: https://pymysql.readthedocs.io/
Python official documentation: https://docs.python.org/3/library/index.html


Guess you like

Origin blog.csdn.net/qq_43341612/article/details/132113053