Home Backend Development Python Tutorial Detailed explanation of examples of Python's data operations on MySQL

Detailed explanation of examples of Python's data operations on MySQL

Apr 27, 2017 am 11:47 AM
mysql python operate

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
Copy after login

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
Copy after login

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()
Copy after login

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()
Copy after login

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()
Copy after login

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()
Copy after login

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()
Copy after login

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()
Copy after login

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()
Copy after login

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()
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 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.

Does Python projects need to be layered? Does Python projects need to be layered? Apr 19, 2025 pm 10:06 PM

Discussion on Hierarchical Structure in Python Projects In the process of learning Python, many beginners will come into contact with some open source projects, especially projects using the Django framework...

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

See all articles