Python3 MySQL Database Connection - PyMySQL Driver
In this article we introduce how Python3 uses PyMySQL to connect to a database and implement simple create, read, update and delete operations.
What is PyMySQL?
PyMySQL is a library used in Python3.x versions to connect to a MySQL server; Python 2 used mysqldb.
PyMySQL follows the Python Database API v2.0 specification and includes a pure-Python MySQL client library.
PyMySQL installation
Before using PyMySQL, we need to make sure it is installed.
PyMySQL download address:https://github.com/PyMySQL/PyMySQL。
If it is not installed yet, we can install the latest version of PyMySQL with the following command:
$ pip3 install PyMySQL
If your system does not support the pip command, you can install it in the following ways:
1. Use the git command to download 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
$ # 现在你可以删除 PyMySQL* 目录
**Note:** Please make sure you have root privileges to install the above module.
During installation you may see the error "ImportError: No module named setuptools", which means setuptools is not installed; you can visithttps://pypi.python.org/pypi/setuptools to find the installation methods for each system.
Example installation on a Linux system:
$ wget https://bootstrap.pypa.io/ez_setup.py $ python3 ez_setup.py
Database connection
Before connecting to the database, please confirm the following:
- You have created the database TESTDB.
- You have created the table EMPLOYEE in the TESTDB database
- The EMPLOYEE table has the fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
- The user name used to connect to the TESTDB database is "testuser" and the password is "test123"; you can set your own or use the root user name and password directly. Use the Grant command for MySQL database user authorization.
- Python has been installed on your machine pymysql module.
- If you are not familiar with SQL statements, you can visit our SQL Basic Tutorial
Example:
The following example connects to the TESTDB database of MySQL:
Example (Python 3.0+)
#!/usr/bin/python3
import
pymysql
Open a database connection
db
=
pymysql
.
connect
(
host
=
'
localhost
'
,
user
=
'
testuser
'
,
password
=
'
test123
'
,
database
=
'
TESTDB
'
)
Use the cursor() method to create a cursor object
cursor
=
db
.
cursor
(
)
Use the execute() method to execute an SQL query
cursor
.
execute
(
"
SELECT VERSION()
"
)
Use the fetchone() method to get a single row of data.
data
=
cursor
.
fetchone
(
)
(
"
Database version : %s
"
%
data
)
Closing the Database Connection
db
.
close
(
)
Running the above script produces the following output:
Database version : 5.5.20-log
Creating a database table
If a database connection exists, we can use the execute() method to create a table in the database; the following creates the EMPLOYEE table:
Example (Python 3.0+)
#!/usr/bin/python3
import
pymysql
Open a database connection
db
=
pymysql
.
connect
(
host
=
'
localhost
'
,
user
=
'
testuser
'
,
password
=
'
test123
'
,
database
=
'
TESTDB
'
)
Use the cursor() method to create a cursor object
cursor
=
db
.
cursor
(
)
Use the execute() method to execute SQL, deleting the table if it exists
cursor
.
execute
(
"
DROP TABLE IF EXISTS EMPLOYEE
"
)
Create the table using a prepared statement
sql
=
"""
CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )
"""
cursor
.
execute
(
sql
)
Closing the Database Connection
db
.
close
(
)
Database insert operation
The following example executes an SQL INSERT statement to insert a record into the EMPLOYEE table:
Example (Python 3.0+)
#!/usr/bin/python3
import
pymysql
Open a database connection
db
=
pymysql
.
connect
(
host
=
'
localhost
'
,
user
=
'
testuser
'
,
password
=
'
test123
'
,
database
=
'
TESTDB
'
)
Use the cursor() method to get an operation cursor
cursor
=
db
.
cursor
(
)
SQL insert statement
sql
=
"""
INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)
"""
try
:
Execute the SQL statement
cursor
.
execute
(
sql
)
Commit to the database for execution
db
.
commit
(
)
except
:
Roll back if an error occurs
db
.
rollback
(
)
Closing the Database Connection
db
.
close
(
)
The above example can also be written in the following form:
Example (Python 3.0+)
#!/usr/bin/python3
import
pymysql
Open a database connection
db
=
pymysql
.
connect
(
host
=
'
localhost
'
,
user
=
'
testuser
'
,
password
=
'
test123
'
,
database
=
'
TESTDB
'
)
Use the cursor() method to get an operation cursor
cursor
=
db
.
cursor
(
)
SQL insert statement
sql
=
"
INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', %s, '%s', %s)
"
% \
(
'
Mac
'
,
'
Mohan
'
,
20
,
'
M
'
,
2000
)
try
:
Execute the SQL statement
cursor
.
execute
(
sql
)
Execute the SQL statement
db
.
commit
(
)
except
:
Roll back when an error occurs
db
.
rollback
(
)
Closing the Database Connection
db
.
close
(
)
The following code passes parameters into an SQL statement using variables:
..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values( %s, %s)' % \
(user_id, password))
..................................
Database query operation
Python queries MySQL using the fetchone() method to get a single row of data and fetchall() to get multiple rows.
- fetchone(): This method gets the next query result set. The result set is an object
- **fetchall(): ** receives all the returned result rows.
- rowcount: This is a read-only attribute and returns the number of rows affected after executing the execute() method.
Example:
Query all data in the EMPLOYEE table where the salary field is greater than 1000:
Example (Python 3.0+)
#!/usr/bin/python3
import
pymysql
Open a database connection
db
=
pymysql
.
connect
(
host
=
'
localhost
'
,
user
=
'
testuser
'
,
password
=
'
test123
'
,
database
=
'
TESTDB
'
)
Use the cursor() method to get an operation cursor
cursor
=
db
.
cursor
(
)
SQL query statement
sql
=
"
SELECT * FROM EMPLOYEE \ WHERE INCOME > %s
"
%
(
1000
)
try
:
Execute the SQL statement
cursor
.
execute
(
sql
)
Get the list of all records
results
=
cursor
.
fetchall
(
)
for
row
in
results
:
fname
=
row
[
0
]
lname
=
row
[
1
]
age
=
row
[
2
]
sex
=
row
[
3
]
income
=
row
[
4
]
Print the result
(
"
fname=%s,lname=%s,age=%s,sex=%s,income=%s
"
% \
(
fname
,
lname
,
age
,
sex
,
income
)
)
except
:
(
"
Error: unable to fetch data
"
)
Closing the Database Connection
db
.
close
(
)
The result of running the above script is as follows:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
Database update operation
Update operations change the data in a table; the following example increments the AGE field by 1 for rows in the TESTDB table where SEX is 'M':
Example (Python 3.0+)
#!/usr/bin/python3
import
pymysql
Open a database connection
db
=
pymysql
.
connect
(
host
=
'
localhost
'
,
user
=
'
testuser
'
,
password
=
'
test123
'
,
database
=
'
TESTDB
'
)
Use the cursor() method to get an operation cursor
cursor
=
db
.
cursor
(
)
SQL update statement
sql
=
"
UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'
"
%
(
'
M
'
)
try
:
Execute the SQL statement
cursor
.
execute
(
sql
)
Commit to the database for execution
db
.
commit
(
)
except
:
Roll back when an error occurs
db
.
rollback
(
)
Closing the Database Connection
db
.
close
(
)
Delete operation
Delete operations remove data from a table; the following example deletes all data in the EMPLOYEE table where AGE is greater than 20:
Example (Python 3.0+)
#!/usr/bin/python3
import
pymysql
Open a database connection
db
=
pymysql
.
connect
(
host
=
'
localhost
'
,
user
=
'
testuser
'
,
password
=
'
test123
'
,
database
=
'
TESTDB
'
)
Use the cursor() method to get an operation cursor
cursor
=
db
.
cursor
(
)
SQL delete statement
sql
=
"
DELETE FROM EMPLOYEE WHERE AGE > %s
"
%
(
20
)
try
:
Execute the SQL statement
cursor
.
execute
(
sql
)
Commit the changes
db
.
commit
(
)
except
:
Roll back when an error occurs
db
.
rollback
(
)
Close the Connection
db
.
close
(
)
Executing transactions
The transaction mechanism ensures data consistency.
A transaction should have four properties: atomicity, consistency, isolation and durability. These four are usually called the ACID properties.
- Atomicity. A transaction is an indivisible unit of work; the operations in a transaction are either all done or none are done.
- Consistency. A transaction must take the database from one consistent 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 inside a transaction are isolated from other concurrent transactions, and concurrently executing transactions cannot interfere with each other.
- Durability. Also called permanence, it 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 effect on it.
The Python DB API 2.0 transaction provides two methods, commit and rollback.
Example
Example (Python 3.0+)
SQL statement to delete records
sql
=
"
DELETE FROM EMPLOYEE WHERE AGE > %s
"
%
(
20
)
try
:
Execute the SQL statement
cursor
.
execute
(
sql
)
Commit to the database
db
.
commit
(
)
except
:
Roll back when an error occurs
db
.
rollback
(
)
For databases that support transactions, in Python database programming an implicit database transaction starts automatically as soon as a cursor is created.
The commit() method commits all update operations of the cursor, and the rollback() method rolls back all operations of the current cursor. Each method starts a new transaction.
Error handling
The DB API defines a number of errors and exceptions for database operations; the following table lists them:
| exception | Description |
|---|---|
| Warning | Raised when there is a serious warning, for example when inserted data is truncated. Must be a subclass of StandardError. |
| Error | The base class of all other errors besides warnings. Must be a subclass of StandardError. |
| InterfaceError | Raised when an error occurs in the database interface module itself (rather than in the database). Must be a subclass of Error. |
| DatabaseError | Raised when a database-related error occurs. Must be a subclass of Error. |
| DataError | Raised when an error occurs during data processing, for example a division by zero or data out of range. Must be a subclass of DatabaseError. |
| OperationalError | Refers to errors that are not under user control but occur while operating the database, such as an unexpected connection loss, a database name not found, a failed transaction or a memory allocation error. Must be a subclass of DatabaseError. |
| IntegrityError | Integrity-related errors, such as a failed foreign key check. Must be a subclass of DatabaseError. |
| InternalError | Internal database errors, such as an invalid cursor or a failed transaction synchronization. Must be a subclass of DatabaseError. |
| ProgrammingError | Programming errors, such as a table not found or already existing, an SQL syntax error or a wrong number of parameters. Must be a subclass of DatabaseError. |
| NotSupportedError | Not supported errors, meaning a function or API not supported by the database was used. For example, calling .rollback() on a connection object when the database does not support transactions or the transaction is closed. Must be a subclass of DatabaseError. |
The following is the inheritance structure of the exceptions:
Exception
|__Warning
|__Error
|__InterfaceError
|__DatabaseError
|__DataError
|__OperationalError
|__IntegrityError
|__InternalError
|__ProgrammingError
|__NotSupportedError