Python MySQL Database Operations
Python's standard database interface is the Python DB-API, which provides developers with a database application programming interface.
Python's database interface supports a great many databases; you can choose the one that suits your project:
- GadFly
- mSQL
- MySQL
- PostgreSQL
- Microsoft SQL Server 2000
- Informix
- Interbase
- Oracle
- Sybase
You can visitPython database interfaces and APIsto view the detailed list of supported databases.
For different databases, you need to download different DB API modules. For example, to access Oracle and MySQL databases, you need to download the Oracle and MySQL database modules.
DB-API is a specification. It defines a set of required objects and database access methods in order to provide a consistent access interface for a wide variety of underlying database systems and diverse database interface programs.
Python's DB-API implements interfaces for most databases. After using it to connect to various databases, you can operate on them all in the same way.
Python DB-API usage flow:
- Import the API module.
- Obtain a connection to the database.
- Execute SQL statements and stored procedures.
- Close the database connection.
What is MySQLdb?
MySQLdb is an interface for connecting Python to MySQL databases. It implements the Python Database API Specification V2.0 and is built on top of the MySQL C API.
How to install MySQLdb?
To write MySQL scripts with DB-API, you must first make sure MySQL is installed. Copy the following code and execute it:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
If the output after execution is as follows, it means the MySQLdb module is not installed:
Traceback (most recent call last):
File "test.py", line 3, in
import MySQLdb
ImportError: No module named MySQLdb
To install MySQLdb, please visit http://sourceforge.net/projects/mysql-python , (on Linux platforms you can visit:https://pypi.python.org/pypi/MySQL-python) From here you can select an installation package suitable for your platform, available as precompiled binaries or source code packages.
If you choose a binary distribution, the installation can basically be completed by following the installation prompts. If installing from source code, you need to switch to the top-level directory of the MySQLdb distribution and type the following commands:
$ gunzip MySQL-python-1.2.2.tar.gz
$ tar -xvf MySQL-python-1.2.2.tar
$ cd MySQL-python-1.2.2
$ python setup.py build
$ python setup.py install
**Note:** Please make sure you have root privileges to install the above module.
Database connection
Before connecting to the database, please confirm the following:
- You have created the database TESTDB.
- In the TESTDB database, you have already created the table EMPLOYEE.
- The fields of the EMPLOYEE table are FIRST_NAME, LAST_NAME, AGE, SEX, and INCOME.
- The username used to connect to the TESTDB database is 'testuser' and the password is 'test123'. You can set these yourself or simply use the root username and its password. To grant MySQL database user permissions, use the Grant command.
- The Python MySQLdb module has been installed on your machine.
- If you are not familiar with SQL statements, you can visit our SQL Basic Tutorial
Example:
The following example connects to the MySQL TESTDB database:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# Get the operation cursor using the cursor() method
cursor = db.cursor()
# Execute SQL statement using the execute method
cursor.execute("SELECT VERSION()")
# Get one record using fetchone() method
data = cursor.fetchone()
print "Database version : %s " % data
# Close database connection
db.close()
Running the above script produces the following output:
Database version : 5.0.45
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:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# Get the operation cursor using the cursor() method
cursor = db.cursor()
# If the data table already exists, use the execute() method to drop the table.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table SQL 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)
# Close database connection
db.close()
Database insert operation
The following example executes an SQL INSERT statement to insert a record into the EMPLOYEE table:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# Get the operation cursor using the cursor() method
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 SQL statement
cursor.execute(sql)
# Submit to database execution
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# Close database connection
db.close()
The above example can also be written in the following form:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# Get the operation cursor using the cursor() method
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 SQL statement
cursor.execute(sql)
# Submit to database execution
db.commit()
except:
# Rollback on error
db.rollback()
# Close database connection
db.close()
Example:
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 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:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# Get the operation cursor using the cursor() method
cursor = db.cursor()
# SQL query statement
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > %s" % (1000)
try:
# Execute SQL statement
cursor.execute(sql)
# Get all records list
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Print result
print "fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fetch data"
# Close 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
An update operation is used to update data in a table. The following example increments the AGE field by 1 for rows in the EMPLOYEE table whose SEX field is 'M':
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# Get the operation cursor using the cursor() method
cursor = db.cursor()
# SQL Update statement
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
# Execute SQL statement
cursor.execute(sql)
# Submit to database execution
db.commit()
except:
# Rollback on error
db.rollback()
# Close 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:
#!/usr/bin/python
-- coding: UTF-8 --
import MySQLdb
Open a database connection
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
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:
# SQL delete record statement
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
# Execute SQL statement
cursor.execute(sql)
# Submit to database
db.commit()
except:
# Rollback on error
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. |