27 Python Database Programming Study Material PDF
27 Python Database Programming Study Material PDF
27 Python Database Programming Study Material PDF
Complete
Python
In
Simple Way
1 https://www.youtube.com/durgasoftware
PYTHON
DATABASE
PROGRAMMING
STUDY MATERIAL
2 https://www.youtube.com/durgasoftware
Storage Areas
As the Part of our Applications, we required to store our Data like Customers Information,
Billing Information, Calls Information etc.
To store this Data, we required Storage Areas. There are 2 types of Storage Areas.
File Systems:
File Systems can be provided by Local operating System. File Systems are best suitable to
store very less Amount of Information.
Limitations:
1) We cannot store huge Amount of Information.
2) There is no Query Language support and hence operations will become very complex.
3) There is no Security for Data.
4) There is no Mechanism to prevent duplicate Data. Hence there may be a chance of Data
Inconsistency Problems.
Databases:
1) We can store Huge Amount of Information in the Databases.
2) Query Language Support is available for every Database and hence we can perform
Database Operations very easily.
3) To access Data present in the Database, compulsory username and pwd must be
required. Hence Data is secured.
4) Inside Database Data will be stored in the form of Tables. While developing Database
Table Schemas, Database Admin follow various Normalization Techniques and can
3 https://www.youtube.com/durgasoftware
implement various Constraints like Unique Key Constrains, Primary Key Constraints etc
which prevent Data Duplication. Hence there is no chance of Data Inconsistency Problems.
Limitations of Databases:
1) Database cannot hold very Huge Amount of Information like Terabytes of Data.
2) Database can provide support only for Structured Data (Tabular Data OR Relational
Data) and cannot provide support for Semi Structured Data (like XML Files) and
Unstructured Data (like Video Files, Audio Files, Images etc)
To overcome these Problems we should go for more Advanced Storage Areas like Big Data
Technologies, Data warehouses etc.
3) To execute our sql queries and to hold results some special object is required, which is
nothing but Cursor object. We can create Cursor object by using cursor() method.
cursor = con.cursor()
4) Execute SQL Queries By using Cursor object. For this we can use the following methods
⚽ execute(sqlquery) To execute a Single SQL Query
⚽ executescript(sqlqueries) To execute a String of SQL Queries seperated by semi-
colon ';'
4 https://www.youtube.com/durgasoftware
⚽ executemany() To execute a Parameterized Query.
Eg: cursor.execute("select * from employees")
5) Commit OR Rollback changes based on our requirement in the case of DML Queries
(insert|update|delete)
6) Fetch the result from the Cursor object in the case of select queries
fetchone() To fetch only one row
fetchall() To fetch all rows and it returns a list of rows
fecthmany(n) To fetch first n rows
Eg 1: data = cursor.fetchone()
print(data)
Eg 2: data = cursor.fetchall()
for row in data:
print(row)
Note: The following is the list of all important methods which can be used for python
database programming.
⚽ connect()
⚽ cursor()
⚽ execute()
⚽ executescript()
⚽ executemany()
⚽ commit()
⚽ rollback()
⚽ fetchone()
⚽ fetchall()
⚽ fetchmany(n)
⚽ fetch
⚽ close()
5 https://www.youtube.com/durgasoftware
These methods won't be changed from database to database and same for all databases.
Diagram
Installing cx_Oracle:
From Normal Command Prompt (But not from Python console) execute the following
command
Collecting cx_Oracle
Downloading cx_Oracle-6.0.2-cp36-cp36m-win32.whl (100kB)
100% |-----------| 102kB 256kB/s
Installing collected packages: cx-Oracle
Successfully installed cx-Oracle-6.0.2
6 https://www.youtube.com/durgasoftware
_sha256 dbm pick turtledemo
_sha3 decimal pickle types
_sha512 demo pickletools typing
_signal difflib pip unicodedata
_sitebuiltins dis pipes unittest
_socket distutils pkg_resources unpick
_sqlite3 doctest pkgutil update
_sre dummy_threading platform urllib
_ssl durgamath plistlib uu
_stat easy_install polymorph uuid
.....
Output
D:\python_classes>py db1.py
11.2.0.2.0
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) cursor.execute("create table employees(eno number,ename varchar2(10),esal n
umber(10,2),eaddr varchar2(10))")
6) print("Table created successfully")
7) except cx_Oracle.DatabaseError as e:
8) if con:
9) con.rollback()
10) print("There is a problem with sql",e)
11) finally:
12) if cursor:
13) cursor.close()
7 https://www.youtube.com/durgasoftware
14) if con:
15) con.close()
8 https://www.youtube.com/durgasoftware
16) con.close()
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) increment=float(input("Enter Increment Salary:"))
6) salrange=float(input("Enter Salary Range:"))
7) sql="update employees set esal=esal+%f where esal<%f"
8) cursor.execute(sql %(increment,salrange))
9) print("Records Updated Successfully")
10) con.commit()
11) except cx_Oracle.DatabaseError as e:
12) if con:
13) con.rollback()
14) print("There is a problem with sql :",e)
15) finally:
16) if cursor:
17) cursor.close()
18) if con:
19) con.close()
10 https://www.youtube.com/durgasoftware
App 7) Write a Program to Delete Employees whose Salary
Greater provided Salary as Dynamic Input?
Eg: delete all employees whose salary > 5000
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) cutoffsalary=float(input("Enter CutOff Salary:"))
6) sql="delete from employees where esal>%f"
7) cursor.execute(sql %(cutoffsalary))
8) print("Records Deleted Successfully")
9) con.commit()
10) except cx_Oracle.DatabaseError as e:
11) if con:
12) con.rollback()
13) print("There is a problem with sql :",e)
14) finally:
15) if cursor:
16) cursor.close()
17) if con:
18) con.close()
11 https://www.youtube.com/durgasoftware
17) if con:
18) con.close()
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) cursor.execute("select * from employees")
6) n=int(input("Enter the number of required rows:"))
7) data=cursor.fetchmany(n)
8) for row in data:
9) print(row)
12 https://www.youtube.com/durgasoftware
10) except cx_Oracle.DatabaseError as e:
11) if con:
12) con.rollback()
13) print("There is a problem with sql :",e)
14) finally:
15) if cursor:
16) cursor.close()
17) if con:
18) con.close()
Output
D:\python_classes>py test.py
Enter the number of required rows:3
(100, 'Durga', 1500.0, 'Hyd')
(200, 'Sunny', 2500.0, 'Mumbai')
(300, 'Chinny', 3500.0, 'Hyd')
D:\python_classes>py test.py
Enter the number of required rows:4
(100, 'Durga', 1500.0, 'Hyd')
(200, 'Sunny', 2500.0, 'Mumbai')
(300, 'Chinny', 3500.0, 'Hyd')
(400, 'Bunny', 4500.0, 'Hyd')
Note: In MySQL, everything we have to work with our own databases, which are also
known as Logical Databases.
In the above diagram only one physical database is available and 4 logical databases are
available.
13 https://www.youtube.com/durgasoftware
Commonly used Commands in MySQL:
1) To Know Available Databases
mysql> show databases;
5) To Create a Table
create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2),
eaddr varchar(10));
6) To Insert Data
insert into employees values(100,'Durga',1000,'Hyd');
insert into employees values(200,'Ravi',2000,'Mumbai');
Driver/Connector Information:
From Python program if we want to communicates with MySql database, compulsory
some translator is required to convert python specific calls into mysql database specific
calls and mysql database specific calls into python specific calls. This translator is nothing
but Driver or Connector.
Note: In the case of Python3.4 we have to set PATH and PYTHONPATH explicitly
PATH=C:\Python34
PYTHONPATH=C:\Python34\Lib\site-packages
14 https://www.youtube.com/durgasoftware
Q) Write a Program to Create Table, Insert Data and display
Data by using MySQL Database
1) import mysql.connector
2) try:
3) con=mysql.connector.connect(host='localhost',database='durgadb',user='root',p
assword='root')
4) cursor=con.cursor()
5) cursor.execute("create table employees(eno int(5) primary key,ename varchar(1
0),esal double(10,2),eaddr varchar(10))")
6) print("Table Created...")
7)
8) sql = "insert into employees(eno, ename, esal, eaddr) VALUES(%s, %s, %s, %s)"
9) records=[(100,'Sachin',1000,'Mumbai'),
10) (200,'Dhoni',2000,'Ranchi'),
11) (300,'Kohli',3000,'Delhi')]
12) cursor.executemany(sql,records)
13) con.commit()
14) print("Records Inserted Successfully...")
15) cursor.execute("select * from employees")
16) data=cursor.fetchall()
17) for row in data:
18) print("Employee Number:",row[0])
19) print("Employee Name:",row[1])
20) print("Employee Salary:",row[2])
21) print("Employee Address:",row[3])
22) print()
23) print()
24) except mysql.connector.DatabaseError as e:
25) if con:
26) con.rollback()
27) print("There is a problem with sql :",e)
28) finally:
29) if cursor:
30) cursor.close()
31) if con:
32) con.close()
15 https://www.youtube.com/durgasoftware
Q) Write a Program to Copy Data present in Employees
Table of MySQL Database into Oracle Database
1) import mysql.connector
2) import cx_Oracle
3) try:
4) con=mysql.connector.connect(host='localhost',database='durgadb',user='root',p
assword='root')
5) cursor=con.cursor()
6) cursor.execute("select * from employees")
7) data=cursor.fetchall()
8) list=[]
9) for row in data:
10) t=(row[0],row[1],row[2],row[3])
11) list.append(t)
12) except mysql.connector.DatabaseError as e:
13) if con:
14) con.rollback()
15) print("There is a problem with MySql :",e)
16) finally:
17) if cursor:
18) cursor.close()
19) if con:
20) con.close()
21)
22) try:
23) con=cx_Oracle.connect('scott/tiger@localhost')
24) cursor=con.cursor()
25) sql="insert into employees values(:eno,:ename,:esal,:eaddr)"
26) cursor.executemany(sql,list)
27) con.commit()
28) print("Records Copied from MySQL Database to Oracle Database Successfully")
16 https://www.youtube.com/durgasoftware
https://dev.mysql.com/downloads/connector/python/2.1.html
17 https://www.youtube.com/durgasoftware