search
HomeBackend DevelopmentPython TutorialDetailed explanation of examples of Python's data operations on MySQL

This article introduces Python3 to use PyMySQL to connect to the database and implement simple additions, deletions, modifications and queries. Has very good reference value. Let’s take a look at it with the editor

This article introduces Python3 to use PyMySQL to connect to the database and implement simple additions, deletions, modifications and queries.

What is PyMySQL?

PyMySQL is a library used to connect to the MySQL server in Python 3.x. Mysqldb is used in Python 2.x.

PyMySQL installation

Before using PyMySQL, we need to make sure that PyMySQL is installed.

PyMySQL download address: https://github.com/PyMySQL/PyMySQL.

If it is not installed yet, we can use the following command to install the latest version of PyMySQL:

$ pip install PyMySQL

If your system does not support it pip command, you can use the following methods to install:

1. Use the git command to download and install the installation package (you can also download it manually):

$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL
$ python3 setup.py install

2. If you need to specify a version number, you can use the curl command to install:

$ # X.X 为PyMySQL 的版本号
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz
$ cd PyMySQL*
$ python3 setup.py install

Note: Please Make sure you have root access to install the above modules.

Database connection

Before connecting to the database, please confirm the following:

  • You have created the database TESTDB

  • In the TESTDB database you have created the table EMPLOYEE

  • The fields of the EMPLOYEE table are FIRST_NAME, LAST_NAME, AGE, SEX and INCOME

  • The user name used to connect to the database TESTDB is "testuser" and the password is "test123". You can set it yourself or directly use the root username and password. For Mysql database user authorization, please use the Grant command

  • The PyMySQL module has been installed on your machine

Example:

The following example links to Mysql TESTDB database:

#!/usr/bin/python3
__author__ = 'mayi'
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)

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

Create database table

If the database connection exists we can use the execute() method to create a table for the database, create table EMPLOYEE as follows:

#!/usr/bin/python3
__author__ = 'mayi'
import pymysql

# 开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

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

# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (
 FIRST_NAME CHAR(20) NOT NULL,
 LAST_NAME CHAR(20),
 AGE INT, 
 SEX CHAR(1),
 INCOME FLOAT )"""
cursor.execute(sql)
# 关闭数据库连接
db.close()

Database insert operation

The following example uses the SQL Insert statement to insert records into the table EMPLOYEE:

#!/usr/bin/python3
__author__ = 'mayi'

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

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

# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
 LAST_NAME, AGE, SEX, INCOME)
 VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
 # 执行sql语句
 cursor.execute(sql)
 # 提交到数据库执行
 db.commit()
except:
 # 如果发生错误则回滚
 db.rollback()

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

The above example can also be written in the following form:

#!/usr/bin/python3
__author__ = 'mayi'

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

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

# SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
 LAST_NAME, AGE, SEX, INCOME) \
 VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
 ('Mac', 'Mohan', 20, 'M', 2000)
try:
 # 执行sql语句
 cursor.execute(sql)
 # 执行sql语句
 db.commit()
except:
 # 发生错误时回滚
 db.rollback()

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

Database query operation

Python queries Mysql using the fetchone() method to obtain a single piece of data, and the fetchall() method to obtain multiple pieces of data.

  • fetchone(): This method gets the next query result set. The result set is an object

  • fetchall(): Receives all returned result rows

  • rowcount: This is a read-only property and returns Number of rows affected after executing execute() method

#Example:

Query all data in the EMPLOYEE table whose salary field is greater than 1000 :

#!/usr/bin/python3
__author__ = 'mayi'

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

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

# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
 WHERE INCOME > '%d'" % (1000)
try:
 # 执行SQL语句
 cursor.execute(sql)
 # 获取所有记录列表
 results = cursor.fetchall()
 for row in results:
 fname = row[0]
 lname = row[1]
 age = row[2]
 sex = row[3]
 income = row[4]
 # 打印结果
 print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
 (fname, lname, age, sex, income ))
except:
 print ("Error: unable to fecth data")

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

Database update operation

The update operation is used to update the data in the data table. The following example will modify all the SEX fields in the TESTDB table to 'M', AGE Field increment by 1:

#!/usr/bin/python3
__author__ = 'mayi'

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

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

# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
 WHERE SEX = '%c'" % ('M')
try:
 # 执行SQL语句
 cursor.execute(sql)
 # 提交到数据库执行
 db.commit()
except:
 # 发生错误时回滚
 db.rollback()

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

Delete operation

The deletion operation is used to delete data in the data table. The following example demonstrates deleting all AGE greater than 20 in the data table EMPLOYEE. Data:

#!/usr/bin/python3
__author__ = 'mayi'

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

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

# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
 # 执行SQL语句
 cursor.execute(sql)
 # 提交修改
 db.commit()
except:
 # 发生错误时回滚
 db.rollback()

# 关闭连接
db.close()

Execute transactions

The transaction mechanism can ensure data consistency.

Transactions should have 4 attributes: atomicity, consistency, isolation, and durability. These four properties are often called ACID properties.

  • Atomicity. A transaction is an indivisible unit of work. All operations included in the transaction are either done or none of them are done.

  • Consistency. A transaction must change the database from one consistency state to another. Consistency and atomicity are closely related.

  • Isolation. The execution of a transaction cannot be interfered with by other transactions. That is, the operations and data used within a transaction are isolated from other concurrent transactions, and transactions executed concurrently cannot interfere with each other.

  • Durability. Continuity, also known as permanence, means that once a transaction is committed, its changes to the data in the database should be permanent. Subsequent operations or failures should not have any impact on it.

Example

# SQL删除记录语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
 # 执行SQL语句
 cursor.execute(sql)
 # 向数据库提交
 db.commit()
except:
 # 发生错误时回滚
 db.rollback()

For databases that support transactions, in Python database programming, when the cursor is created, an invisible process is automatically started. database transactions.

The commit() method performs all update operations on the cursor, and the rollback() method rolls back all operations on the current cursor. Each method starts a new transaction.

Error handling

Exception Description
Warning Triggered when there is a serious warning, for example, inserting data is Truncated and so on. Must be a subclass of StandardError.
Error All other error types except warning. Must be a subclass of StandardError.
InterfaceError Triggered when an error occurs in the database interface module itself (not an error in the database). Must be a subclass of Error.
DatabaseError Triggered when an error related to the database occurs. Must be a subclass of Error.
DataError Triggered when an error occurs during data processing, such as: division by zero error, data out of range, etc. Must be a subclass of DatabaseError.
OperationalError refers to errors that are not controlled by the user, but occur when operating the database. For example: the connection is unexpectedly disconnected, the database name is not found, transaction processing fails, memory allocation errors, etc. are errors that occur when operating the database. Must be a subclass of DatabaseError.
IntegrityError Integrity-related errors, such as foreign key check failure, etc. Must be a DatabaseError subclass.
InternamError Internal errors in the database, such as cursor failure, transaction synchronization failure, etc. Must be a DatabaseError subclass.
ProgrammingError Programming errors, such as the data table (table) is not found or already exists, SQL statement syntax error, wrong number of parameters, etc. Must be a subclass of DatabaseError.
NotSupportedError Not supported error refers to the use of functions or APIs that are not supported by the database. For example, the rollback() function is used on the connection object, but the database does not support transactions or the transaction has been closed. Must be a subclass of DatabaseError.

The above is the detailed content of Detailed explanation of examples of Python's data operations on MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.