PythonDatabase
PythonDatabase
Most Python
database interfaces adhere to this standard.
You can choose the right database for your application. Python Database API
supports a wide range of database servers such as −
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
SQLite
For example, if you need to access an Oracle database as well as a MySQL database,
you must download both the Oracle and the MySQL database modules.
The DB API provides a minimal standard for working with databases using Python
structures and syntax wherever possible. This API includes the following:
Importing the API module.
Acquiring a connection with the database.
Issuing SQL statements and stored procedures.
Closing the connection
Python has an in-built support for SQLite. In this section, we would learn all the
concepts using MySQL. MySQLdb module, a popular interface with MySQL is not
compatible with Python 3. Instead, we shall use PyMySQL module.
What is PyMySQL ?
import PyMySQL
If it produces the following result, then it means MySQLdb module is not installed-
Traceback (most recent call last):
File “test.py”, line 3, in <module>
Import PyMySQL
ImportError: No module named PyMySQL
The last stable release is available on PyPI and can be installed with pip:
Database Connection
Before connecting to a MySQL database, make sure of the following points-
You have created a database TESTDB.
You have created a table EMPLOYEE in TESTDB.
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
Python module PyMySQL is installed properly on your machine.
Example
Following is an example of connecting with MySQL database "TESTDB"-
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)
# disconnect from server
db.close()
import PyMySQL
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()
INSERT Operation
The INSERT Operation is required when you want to create your records into a
databasetable.
Example
The following example, executes SQL INSERT statement to create a record in the
EMPLOYEE table-
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Example
The following procedure queries all the records from EMPLOYEE table having salary
more than 1000-
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income ))
except:
print ("Error: unable to fecth data")
# disconnect from server
db.close()