PART-B
ESSAY QUESTIONS WITH SOLUTIONS
5.1 INTRODUCTION
06. Give a detail description about database programming.
Answer t 010
Data bases can be defined as the collections of tables that are connected with each other through columns. The b&ic
concepts of database programming are as follows,
1. Persistent Storage
All the applications need persistent storage. The basic types ofstorage mechanisms are files. relational database system
(RDBMS) and a type of hybrid spreadsheet, Object relational mapper
ie., an API that is root of existing systems, file manager,
(ORM), configuration file etc.
2. Basic Database Operations and SQL
Some of the elementary database concepts and SQL are illustrated as follows,
Underlying Storage
All the databases have fundamental persistent storage by using the file system. Examples of it are special operating
system files, normal operating system files and raw disk partitions.
User Interface
A command line tool is used for SQL commands and queries. This tool is provided by theaatabase
systems. Even
the GUI tools make use of command line clients or database client library so that the users are
provided with an
easy interface.
(iii) Databases
Thé RDBMS has the ability to manage various databases such as customer support, sales,
marketing etc at a time on
one server.The MYSQL is an example of server based RDBMS because it consists ofserver process
that is running
continuously.
(iv) Components
Databases consists of tables as storage abstractions. And every table consists of
rows and columns. A data base
schema can be defined as set of table definitions of columns and data types together.
The dmabases and tables can
be created and deleted as well. It is even possible to perform various
operations such as insertion, updation, deletion
etc on them.
(v) SQL
SQL provides database commands and queries to the database.
Various database commands in SQL are as follows,
Create Database
CREATE DATABASE SCHOOL;
GRANT ALL ON SCHOOL. • user(s);
It creates a database with name SCHOOL and grants permission
to specific users in order to perform database
operations.
Use a Database
USE SCHOOL;
It specifies the database that is to be used for performing operations.
prop 'he
DHOP datøl•aøe SCHOOL',
j/ deletes database and fables from the "Stem,
Create
INT. NAME
ji creates Anew table with columns ID and NAME,
Drop ATable
DROP TABLE
deictegthe table completely along with the data.
Insert a Row
INSERT INTO VALUESC21',
It inserts a row in the table.
Update ARow
UPI)AI'E SCHOOLSET NAME-
WHERE id •• 4;
It modifies and updates the values of specified row.
Delete g Row
DELETE FROM SCHOOL WHERE id - 2;
It deletes the data of specified row.
3. Databases and Python
The users are allowed to access RI)BMS from Python directly by using the database interface or through an ORM.
python applications can be integrated with some type of database system. The data can be stored and retrjeved tolfrmn
RDBM's while working in Python frame work. An adapter is used to access the databae from Python. It is a Python module
that enables users to interface with relational database's client library.
Python application Python application
Application (em- (embedded SQL) (little or no SQL)
bedded SQL) Python ORM
Python DB adapter
Python DB adapter
RDBMS client RDBMS client RDBMS client
library library library
Relational database
(RDBMS)
Figure: Communication between Application and Database
SPECTRUMRLL-IN-O" JOURNRL FOR ENGINEERING STUDENTS SIA GRwP
5.2 PYTHON DATABASEAPPLICA"ON pg0GRAMMER'SINTERFACE (DO- AP')
Q'. Explain in detail about database application programmers
Database Appbc•tieø Programmer's Interface (DB-API)
access mechanisms for rvoviding access to
API is a which defines a yet of objects as well as •Etabasc interest group). lhs API
different Ltahue SIG (a srecsal
and database systems. The API is
among the databases is sunple amt needs
prong
rtovid.ng consvstent interface to different relational datatuses. Ibe
very les code.
I. Attributes
DB-API complaint rn«xlule defines the txlow define global attnbutes.
Attributes Description
Aptlevel It mdtcates the verston of DB-API with which the
mcxiule has complatnt.
Paramstyle it represents the SQL statement parameter style
of this module. Examples of vanous paramstyles are
qrnark, format. numeric pyformat, named etc.
Connect It is a function that is used to access the database
with connecuon objects.
It indicates the level of thread satety of the module
The exceptions that are included in complaint module
as globals are error. waming, database error etc.
2. Connection Objects
C€nrrctiors usually depict trr communication between the users and the database are the communic ation mechamsms
that send commands to the server. Initially connections are established and then cursors are crea ted to se nd and receive requests
respectively. Various methods of connection objects are as follows,
Method Name Description
Cursor) It creates a cursor
Commit() It commits the transaction
It closes the database connection
Rollback() It cancels the current transaction
Errorhandler(cxn, It serves as handler for specified
encls. curerrval) specified connection cursor.
3. Cursor Objects
The Python DB-API cursor object acts as cursor for the users. Once they are created users can execute the queriesand
retrieve data from result set. The data attributes and methods of cursor objects are as follows.
Attribute Description
Connection It is the connection that creates the cursor.
Row count It indicates the number of rows generated by last execute O
Array size It indicates number of rows to searching through fetch many O
Close() It closes the cursor
Next() Jt is used by iterator to search the next row of query result.
Execute(op (, It executes command or database query
Messages It indicates set of messages that the database contains for
for cursor execution
Fetch one It fetches the next row of query result
Next set() It moves to next results set
Callproc(fun C t, argsJ) It calls the stored prcxedure
Set input-sizes (sizes) it sets the maximum input size that is allowed
Look for the SIA GROUP LOGO on,the TITLE COVER buys
Programming
UNIT-5 Database 5.7
•rypeObjects and Constructors
The python objects and native data objects are related with each other. When the
programmer sends any parameters to
database, they witl reach in the form of strings. need to bc converted into some other data types compatible
with the query.
DBAPI also needs to create the constructors that in turn create special objects. These objects can be easily
The type objects that are used for this purpose arc as follows, converted to
databaseobjects.
Type Object Description
Date from Ticks (ticks) It indicates the date object as per the given number
of seconds from epoch.
Date(yr, mo. dy) It indicates object for date value.
Time(hr, min, sec) It indicates the object from time value.
Timestamp(Yr, mo, dy, hr. min, sec) It indicates the object for timestamp value.
Time stamp from ticks(ticks) It indicates object as per number of seconds
from epoch.
Time from ticks(ticks) It indicates the time object as per number of seconds
from epoch.
NUMBER It indicates the object that represents numeric columns.
STRING It indicates the object that represents the string based
columns.
ROWID It indicates the object that represents 'row ID' columns.
BINARY It indicates the object that represents binary columns.
DATETIME It indicates the object that represents data/time columns.
5. Relational Databases
The database systems that are accessible to interfaces in Python are as follows,
Commercial RDBMSs open Source RDBMSs Database APIs
SAP SQlite ODBC
Sybase Gadifly JDBC
Informix MySQL
Oracle Postgre SQL
DB12
Interbase
MSSQL server
Ingres
6. Databases and Python: Adapters
The adapter is responsible for the connection between the database system and python. The databases like SAP, SQL
server, Sybase, Oracle etc., have multiple adapters. If there are multiple adapters provided for any database system, then the best
among them must be selected based on their features.
SPECTRUMRU-IN-ONE JOURNRL FOR ENGINEERING STUDENTS SIA GROUP
MANAOERO(ORM.).
00. Ol•eu•• •bout obi•et relationalmanagers.
ORM
ORM stand' managers, are various types Of database systems that enable users to maintain
to hame" poweq (bey need some KnowledgeOf SVC If the programmer can manipulate
thon than queries apd need database then ORM would be a best option.
and perform
"these are destgned in way that users can manipulate the Objects tasks, tables are
converted to Classes columns attributes and methods as database operations. The application can he
features and
to an ORM comples and even need more lines of code than using an adapter directly because
operations ('light be
they are.
OR A or work bett•lt' of users 'here arg two ORM's that are used more frequently.
, SQU Obje€t
SQL Atehemy
Other Python ORM's are Durus, POO. Oejavu. PyD(VPy002. Qi,imc. Forget SQL etc. Certain web based systems can
their own ORM component webware middle kit and Django's database API.
Example
SOLAlchemyORM
import os
random import randrange as rrange
from sqlalchemy import
from ushume_db import NAMES. randName
FIELDS ('login'. •uid%'prid')
- 'test'
COLSIZ - 10
class MySQLAlchemy(objcct):
def db. dbName):
import MySQLdb
import _mysql_exccptions
MySQLdb pool.manage(MySQLdb)
url — DBNAME
eng create_engine(url)
try:
exn eng.connection()
except _mysql_excepuons.OperationalError, e:
eng t ••
Look for the GROUP LOGO on the TITLE COVER beforeyoubu
engi .exeeute('DROP DATABASE % DIINAME.)
except _mysqieexcepåonsOperatiooalErtot, e:
DATABASE %
engl.esecute( "ORAVt ALL ON %s.• % DBNAME)
eng I.eomniit()
esn • eng.eonnection()
eng. autoload-True)
users Tablefilsers'.
e:
except exceptions.SQLError,
eng, String(8)). Column('uid'. Integer). Column('prid'. Integer), redefine—True)
users •
self.eng •neng
self.cxn cxn
self.usets •e users
defcreate(self):
usets self.users
users.drop()
e:
except exceptions.SQLError,
users.create()
def insert(selD:
d uid, for who, uid in randName()]
return
def update(selt):
users self.users
fr rrange( I
to rrange(l,5)
return fr, to, \
SPECTRUMALL-IN-ONEJOURML FOR ENGINEERING STUDENTS SIA GROUP
der delete!self);
users self.users
rm rrange(l.S)
return tm, \
def dbDump(selO:
res
print % ('LOGINAjust(COLSIZ), 'USERID'.ljust(COLSJZ).
for data in res.fetchall():
print % (COLSIZ) for s in datal)
attr):
return getattr(self.users, attr)
def finish(seli):
self.cxn.commit()
self.eng.commit()
def main():
print Connecting to %r database' % DBNAME
orm —MySQLAlchemy('mysql', DBNAME)
print '\n••• Creating users table' orm.create()
print '\n••• Inserting names into table'
orm. insert()
orm.dbDump()
print '\n••• Randomly moving folks',fr, to, num = orm.update()
print 'from one group (%d) to another (%d)' % (fr, to)
print '\t(%d users moved)' % num
orm.dbDump()
print '\n••• Randomly choosing group', rm, num = orm.delete()
print '(%d) to delete' % rm
print users removed)' % num
orm.dbDump()
Dropping users table'
SQLObjeet ORM
import
from random- import randrange rrange
from sqlobjectimr»rt •
from ushume_db import NAMES, randName
DBNAME = 'test'
COLSIZ = 10
FIELDS —('login', 'uid', 'prid')
class MySQLObject(object):
def _init_(self, db, dbName):
import MySQLdb
import _mysql_exceptions
url % DBNAME
while Trues.
cxn connectionForURI(urI)
sqlhub.processConnection = cxn
#cxn.debug Tn.E
class Users(SQLObjectY.
class sqlmeta:
fromDatabase True
login StringCol(length—8)
—IntCol()
—IntCol()
except _mysql_exceptions.ProgrammingError, e•.
clus Users(SQLObject):
SPECTRUMALL-IN-ONE )OURML FOR ENQINEERINQ STUDENTS stm GROUP
s.i2
logm
uid IntCol()
prid •eIntCol()
e:
_mysql_exceptions.OperationalError.
except
exnl sqlhub.processConnection—
% DBNAME)
cxnl .queryC'CREATEDATABASE
% DBNAME)
cxnl ALL ON %s.• TO
cxn I .elose()
self.users Users
self.cxn —cxn
def create(sei f):
Users self.users
Users.dropTable(True)
Users.createTable()
def insert(selO:
for who, uid in randName():
uid, rrange(l,5)J)))
def update(selt):
fr rrange( I ,5)
to —rrange(l,5)
users = self.users.selectBy(prid=fr)
for i, user in enumerate(users):
user.prid = to
return fr, to, i+l
def delete(self):
rm = rrange(l,5)
users = self.users.selectBy(prid=rm)
for i, .user in enumerate(users):
Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuye
user.dgstroySelf()
return rm, i+l
def
print % 'PROF.IÄCOLSIZ))
for usr in self.users.select():
print % \for field in FIELDS)))
drop = lambda self: self.users.dropTable()
finish = lambda self: self.cxn.close()
def main():
print Connecting to %r database' % DBNAME
orm = MySQLObject('mysql i, DBNAME)
print Creating users table'
orm.create()
print '\n••• Inserting names into table'
orm.insert()
orm.dbDump()
print '\n••• Randomly moving folks',fr, to, num = orm.update()
print 'from one group (%d) to another % (fr, to)
print users moved)' % num
orm.dbDump()
print '\n••• Randomly choosing group',rm, num orm.delete()
print '(%d) to delete' % rm
print users removed)' % num
orm.dbDump()
print Dropping users table'
orm.drop()
orm.finish()
if name main
main()
SPECTRUMRU-IN-ONE JOURNRL FOR ENGINEERING STUDENTS -..-....-......-....-........-..-.--....-.......„--....-.-
GROUP
5.4 REI-ATCO MODULES
Q'. List out various related modules of database programming,
depicted follow,
The most commeutiy used relatnf mcxlule•sand datat.ses that work in database programming
MYSQI. PypgSQt.
o.dfly Psycopg
PypgSQL
Psyeopg 2 PostgreSQI„
MYSQL.python
SQL-ite adodbapi
APSW sybase
sqlite3 Sybase
pysqlite oracle
sapdb Dcoracle2
sdb ex oracle
MaxDB(SAD) ingres DB!
KlnterbasDB ORMS
pymssql ingmod
SQLserver SQLAlchemy
Fire bird(lnterbase) PyDO/PyD02 SQL object