0% found this document useful (0 votes)
13 views

PythonDatabase

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

PythonDatabase

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

The Python standard for database interfaces is the Python DB-API.

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

Here is the list of available Python database interfaces: Python Database


Interfaces and APIs. You must download a separate DB API module for each database
you need to access.

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 ?

PyMySQL is an interface for connecting to a MySQL database server from Python. It


implements the Python Database API v2.0 and contains a pure-Python MySQL client
library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb .

How do I Install PyMySQL?


Before proceeding further, you make sure you have PyMySQL installed on your
machine. Just type the following in your Python script and execute it-

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:

pip install PyMySQL

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()

Creating Database Table

Once a database connection is established, we are ready to create tables or records


into the database tables using execute method of the created cursor.

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()

You might also like