Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
91 views

Python Notes - 4

The document discusses various synchronization mechanisms in Python including Lock, RLock, Semaphore, and inter-thread communication using Events and Conditions. It explains that Lock allows only one thread to acquire it at a time while RLock allows the owning thread to acquire it multiple times for recursive functions. Semaphore allows a fixed number of threads specified during object creation. Events and Conditions are used for inter-thread communication, with Conditions requiring an associated lock. Events use set() and clear() to signal threads waiting with wait(), while Conditions use acquire(), wait(), notify(), and release().

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Python Notes - 4

The document discusses various synchronization mechanisms in Python including Lock, RLock, Semaphore, and inter-thread communication using Events and Conditions. It explains that Lock allows only one thread to acquire it at a time while RLock allows the owning thread to acquire it multiple times for recursive functions. Semaphore allows a fixed number of threads specified during object creation. Events and Conditions are used for inter-thread communication, with Conditions requiring an associated lock. Events use set() and clear() to signal threads waiting with wait(), while Conditions use acquire(), wait(), notify(), and release().

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

12)

13) def results(n):


14) print("The Factorial of",n,"is:",factorial(n))
15)
16) t1=Thread(target=results,args=(5,))
17) t2=Thread(target=results,args=(9,))
18) t1.start()
19) t2.start()

Output:
The Factorial of 5 is: 120
The Factorial of 9 is: 362880

In the above program instead of RLock if we use normal Lock then the thread will be blocked.

Difference between Lock and RLock:


table

Lock:
1. Lock object can be acquired by only one thread at a time.Even owner thread also cannot acquire
multiple times.
2. Not suitable to execute recursive functions and nested access calls
3. In this case Lock object will takes care only Locked or unlocked and it never takes care
about owner thread and recursion level.

RLock:
1. RLock object can be acquired by only one thread at a time, but owner thread can acquire same
lock object multiple times.
2. Best suitable to execute recursive functions and nested access calls
3. In this case RLock object will takes care whether Locked or unlocked and owner
thread information, recursiion level.

Synchronization by using Semaphore:


In the case of Lock and RLock,at a time only one thread is allowed to execute.

Sometimes our requirement is at a time a particular number of threads are allowed to access(like
at a time 10 memebers are allowed to access database server,4 members are allowed to access
Network connection etc).To handle this requirement we cannot use Lock and RLock concepts and
we should go for Semaphore concept.

Semaphore can be used to limit the access to the shared resources with limited capacity.

Semaphore is advanced Synchronization Mechanism.


We can create Semaphore object as follows.

s=Semaphore(counter)

Here counter represents the maximum number of threads are allowed to access simultaneously.
The default value of counter is 1.

Whenever thread executes acquire() method,then the counter value will be decremented by 1 and
if thread executes release() method then the counter value will be incremented by 1.

i.e for every acquire() call counter value will be decremented and for every release() call counter
value will be incremented.

Case-1: s=Semaphore()
In this case counter value is 1 and at a time only one thread is allowed to access. It is exactly same
as Lock concept.

Case-2: s=Semaphore(3)
In this case Semaphore object can be accessed by 3 threads at a time.The remaining threads have
to wait until releasing the semaphore.

Eg:

1) from threading import *


2) import time
3) s=Semaphore(2)
4) def wish(name):
5)s.acquire()
6)for i in range(10):
7) print("Good Evening:",end='')
8) time.sleep(2)
9) print(name)
10)s.release()
11)
12) t1=Thread(target=wish,args=("Dhoni",))
13) t2=Thread(target=wish,args=("Yuvraj",))
14) t3=Thread(target=wish,args=("Kohli",))
15) t4=Thread(target=wish,args=("Rohit",))
16) t5=Thread(target=wish,args=("Pandya",))
17) t1.start()
18) t2.start()
19) t3.start()
20) t4.start()
21) t5.start()

In the above program at a time 2 threads are allowed to access semaphore and hence 2 threads
are allowed to execute wish() function.
BoundedSemaphore:
Normal Semaphore is an unlimited semaphore which allows us to call release() method any
number of times to increment counter.The number of release() calls can exceed the number of
acquire() calls also.

Eg:

1) from threading import *


2) s=Semaphore(2)
3) s.acquire()
4) s.acquire()
5) s.release()
6) s.release()
7) s.release()
8) s.release()
9) print("End")

It is valid because in normal semaphore we can call release() any number of times.

BounedSemaphore is exactly same as Semaphore except that the number of release() calls should
not exceed the number of acquire() calls,otherwise we will get

ValueError: Semaphore released too many times

Eg:

1) from threading import *


2) s=BoundedSemaphore(2)
3) s.acquire()
4) s.acquire()
5) s.release()
6) s.release()
7) s.release()
8) s.release()
9) print("End")

ValueError: Semaphore released too many times


It is invalid b'z the number of release() calls should not exceed the number of acquire() calls in
BoundedSemaphore.

Note: To prevent simple programming mistakes, it is recommended to use BoundedSemaphore


over normal Semaphore.

Difference between Lock and Semaphore:


At a time Lock object can be acquired by only one thread, but Semaphore object can be acquired
by fixed number of threads specified by counter value.

Conclusion:

The main advantage of synchronization is we can overcome data inconsistency problems.But the
main disadvantage of synchronization is it increases waiting time of threads and creates
performance problems. Hence if there is no specific requirement then it is not recommended to
use synchronization.

Inter Thread Communication:


Some times as the part of programming requirement, threads are required to communicate with
each other. This concept is nothing but interthread communication.

Eg: After producing items Producer thread has to communicate with Consumer thread to notify
about new item.Then consumer thread can consume that new item.

In Python, we can implement interthread communication by using the following ways

1. Event
2. Condition
3. Queue
etc

Interthread communication by using Event Objects:


Event object is the simplest communication mechanism between the threads. One thread signals
an event and other thereds wait for it.

We can create Event object as follows...

event = threading.Event()

Event manages an internal flag that can set() or clear()


Threads can wait until event set.

Methods of Event class:


1. set()  internal flag value will become True and it represents GREEN signal for all
waiting threads.

2. clear()  inernal flag value will become False and it represents RED signal for all
waiting threads.

3. isSet()  This method can be used whether the event is set or not
4. wait()|wait(seconds)  Thread can wait until event is set

Pseudo Code:
event = threading.Event()

#consumer thread has to wait until event is set


event.wait()

#producer thread can set or clear event


event.set()
event.clear()

Demo Program-1:

1) from threading import *


2) import time
3) def producer():
4) time.sleep(5)
5) print("Producer thread producing items:")
6) print("Producer thread giving notification by setting event")
7) event.set()
8) def consumer():
9) print("Consumer thread is waiting for updation")
10) event.wait()
11) print("Consumer thread got notification and consuming items")
12)
13) event=Event()
14) t1=Thread(target=producer)
15) t2=Thread(target=consumer)
16) t1.start()
17) t2.start()

Output:
Consumer thread is waiting for updation
Producer thread producing items
Producer thread giving notification by setting event
Consumer thread got notification and consuming items

Demo Program-2:

1) from threading import *


2) import time
3) def trafficpolice():
4) while True:
5) time.sleep(10)
6) print("Traffic Police Giving GREEN Signal")
7) event.set()
8) time.sleep(20)
9) print("Traffic Police Giving RED Signal")
10) event.clear()
11) def driver():
12) num=0
13) while True:
14) print("Drivers waiting for GREEN Signal")
15) event.wait()
16) print("Traffic Signal is GREEN...Vehicles can move")
17) while event.isSet():
18) num=num+1
19) print("Vehicle No:",num,"Crossing the Signal")
20) time.sleep(2)
21) print("Traffic Signal is RED...Drivers have to wait")
22) event=Event()
23) t1=Thread(target=trafficpolice)
24) t2=Thread(target=driver)
25) t1.start()
26) t2.start()

In the above program driver thread has to wait until Trafficpolice thread sets event.ie until giving
GREEN signal.Once Traffic police thread sets event(giving GREEN signal),vehicles can cross the
signal.Once traffic police thread clears event (giving RED Signal)then the driver thread has to wait.

Interthread communication by using Condition Object:


Condition is the more advanced version of Event object for interthread communication.A
condition represents some kind of state change in the application like producing item or
consuming item. Threads can wait for that condition and threads can be notified once condition
happend.i.e Condition object allows one or more threads to wait until notified by another thread.

Condition is always associated with a lock (ReentrantLock).


A condition has acquire() and release() methods that call the corresponding methods of the
associated lock.

We can create Condition object as follows


condition = threading.Condition()

Methods of Condition:
1. acquire()  To acquire Condition object before producing or consuming items.i.e
thread acquiring internal lock.

2. release()  To release Condition object after producing or consuming items. i.e thread
releases internal lock

3. wait()|wait(time)  To wait until getting Notification or time expired


4. notify()  To give notification for one waiting thread

5. notifyAll()  To give notification for all waiting threads

Case Study:
The producing thread needs to acquire the Condition before producing item to the resource and
notifying the consumers.

#Producer Thread
...generate item..
condition.acquire()
...add item to the resource...
condition.notify()#signal that a new item is available(notifyAll())
condition.release()

The Consumer must acquire the Condition and then it can consume items from the resource

#Consumer Thread
condition.acquire()
condition.wait()
consume item
condition.release()

Demo Program-1:

1) from threading import *


2) def consume(c):
3) c.acquire()
4) print("Consumer waiting for updation")
5) c.wait()
6) print("Consumer got notification & consuming the item")
7) c.release()
8)
9) def produce(c):
10) c.acquire()
11) print("Producer Producing Items")
12) print("Producer giving Notification")
13) c.notify()
14) c.release()
15)
16) c=Condition()
17) t1=Thread(target=consume,args=(c,))
18) t2=Thread(target=produce,args=(c,))
19) t1.start()
20) t2.start()
Output:
Consumer waiting for updation
Producer Producing Items
Producer giving Notification
Consumer got notification & consuming the item

Demo Program-2:

1) from threading import *


2) import time
3) import random
4) items=[]
5) def produce(c):
6)while True:
7) c.acquire()
8) item=random.randint(1,100)
9) print("Producer Producing Item:",item)
10) items.append(item)
11) print("Producer giving Notification")
12) c.notify()
13) c.release()
14) time.sleep(5)
15)
16) def consume(c):
17)while True:
18) c.acquire()
19) print("Consumer waiting for updation")
20) c.wait()
21) print("Consumer consumed the item",items.pop())
22) c.release()
23) time.sleep(5)
24)
25) c=Condition()
26) t1=Thread(target=consume,args=(c,))
27) t2=Thread(target=produce,args=(c,))
28) t1.start()
29) t2.start()

Output:
Consumer waiting for updation
Producer Producing Item: 49
Producer giving Notification
Consumer consumed the item 49
.....

In the above program Consumer thread expecting updation and hence it is responsible to call
wait() method on Condition object.
Producer thread performing updation and hence it is responsible to call notify() or notifyAll() on
Condition object.
Interthread communication by using Queue:
Queues Concept is the most enhanced Mechanism for interthread communication and to share
data between threads.

Queue internally has Condition and that Condition has Lock.Hence whenever we are using Queue
we are not required to worry about Synchronization.

If we want to use Queues first we should import queue module.

import queue

We can create Queue object as follows

q = queue.Queue()

Important Methods of Queue:


1. put(): Put an item into the queue.
2. get(): Remove and return an item from the queue.

Producer Thread uses put() method to insert data in the queue. Internally this method has logic to
acquire the lock before inserting data into queue. After inserting data lock will be released
automatically.

put() method also checks whether the queue is full or not and if queue is full then the Producer
thread will entered in to waiting state by calling wait() method internally.

Consumer Thread uses get() method to remove and get data from the queue. Internally this
method has logic to acquire the lock before removing data from the queue.Once removal
completed then the lock will be released automatically.

If the queue is empty then consumer thread will entered into waiting state by calling wait()
method internally.Once queue updated with data then the thread will be notified automatically.

Note:
The queue module takes care of locking for us which is a great advantage.

Eg:

1) from threading import *


2) import time
3) import random
4) import queue
5) def produce(q):
6) while True:
7) item=random.randint(1,100)
8) print("Producer Producing Item:",item)
9) q.put(item)
10) print("Producer giving Notification")
11) time.sleep(5)
12) def consume(q):
13) while True:
14) print("Consumer waiting for updation")
15) print("Consumer consumed the item:",q.get())
16) time.sleep(5)
17)
18) q=queue.Queue()
19) t1=Thread(target=consume,args=(q,))
20) t2=Thread(target=produce,args=(q,))
21) t1.start()
22) t2.start()

Output:
Consumer waiting for updation
Producer Producing Item: 58
Producer giving Notification
Consumer consumed the item: 58

Types of Queues:
Python Supports 3 Types of Queues.

1. FIFO Queue:
q = queue.Queue()

This is Default Behaviour. In which order we put items in the queue, in the same order the items
will come out (FIFO-First In First Out).

Eg:

1) import queue
2) q=queue.Queue()
3) q.put(10)
4) q.put(5)
5) q.put(20)
6) q.put(15)
7) while not q.empty():
8) print(q.get(),end=' ')

Output: 10 5 20 15
2. LIFO Queue:
The removal will be happend in the reverse order of insertion(Last In First Out)

Eg:

1) import queue
2) q=queue.LifoQueue()
3) q.put(10)
4) q.put(5)
5) q.put(20)
6) q.put(15)
7) while not q.empty():
8) print(q.get(),end=' ')

Output: 15 20 5 10

3. Priority Queue:
The elements will be inserted based on some priority order.

1) import queue
2) q=queue.PriorityQueue()
3) q.put(10)
4) q.put(5)
5) q.put(20)
6) q.put(15)
7) while not q.empty():
8) print(q.get(),end=' ')

Output: 5 10 15 20

Eg 2: If the data is non-numeric, then we have to provide our data in the form of tuple.

(x,y)

x is priority
y is our element

1) import queue
2) q=queue.PriorityQueue()
3) q.put((1,"AAA"))
4) q.put((3,"CCC"))
5) q.put((2,"BBB"))
6) q.put((4,"DDD"))
7) while not q.empty():
8) print(q.get()[1],end=' ')
Output: AAA BBB CCC DDD

Good Programming Practices with usage of Locks:


Case-1:

It is highly recommended to write code of releasing locks inside finally block.The advantage is lock
will be released always whether exception raised or not raised and whether handled or not
handled.

l=threading.Lock()
l.acquire()
try:
perform required safe operations
finally:
l.release()

Demo Program:

1) from threading import *


2) import time
3) l=Lock()
4) def wish(name):
5)l.acquire()
6)try:
7) for i in range(10):
8) print("Good Evening:",end='')
9) time.sleep(2)
10) print(name)
11)finally:
12) l.release()
13)
14) t1=Thread(target=wish,args=("Dhoni",))
15) t2=Thread(target=wish,args=("Yuvraj",))
16) t3=Thread(target=wish,args=("Kohli",))
17) t1.start()
18) t2.start()
19) t3.start()

Case-2:

It is highly recommended to acquire lock by using with statement. The main advantage of with
statement is the lock will be released automatically once control reaches end of with block and we
are not required to release explicitly.

This is exactly same as usage of with statement for files.


Example for File:

with open('demo.txt','w') as f:
f.write("Hello...")

Example for Lock:

lock=threading.Lock()
with lock:
perform required safe operations
lock will be released
automatically

Demo Program:

1) from threading import *


2) import time
3) lock=Lock()
4) def wish(name):
5)with lock:
6) for i in range(10):
7) print("Good Evening:",end='')
8) time.sleep(2)
9) print(name)
10) t1=Thread(target=wish,args=("Dhoni",))
11) t2=Thread(target=wish,args=("Yuvraj",))
12) t3=Thread(target=wish,args=("Kohli",))
13) t1.start()
14) t2.start()
15) t3.start()

Q. What is the advantage of using with statement to acquire a lock in threading?


Lock will be released automatically once control reaches end of with block and We are not
required to release explicitly.

Note: We can use with statement in multithreading for the following cases:

1. Lock
2. RLock
3. Semaphore
4. Condition
Python Database Programming
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.

1) Temporary Storage Areas


2) Permanent Storage Areas

1. Temporary Storage Areas:

These are the Memory Areas where Data will be stored temporarily.
Eg: Python objects like List, Tuple, Dictionary.

Once Python program completes its execution then these objects will be destroyed automatically
and data will be lost.

2. Permanent Storage Areas:

Also known as Persistent Storage Areas. Here we can store Data permanently.
Eg: File Systems, Databases, Data warehouses, Big Data Technologies etc

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.

To overcome the above Problems of File Systems, we should go for Databases.

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 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.

Python Database Programming:


Sometimes as the part of Programming requirement we have to connect to the database and we
have to perform several operations like creating tables, inserting data,updating data,deleting
data,selecting data etc.

We can use SQL Language to talk to the database and we can use Python to send those SQL
commands to the database.

Python provides inbuilt support for several databases like Oracle, MySql, SqlServer, GadFly, sqlite,
etc.
Python has seperate module for each database.
Eg: cx_Oralce module for communicating with Oracle database
pymssql module for communicating with Microsoft Sql Server

Standard Steps for Python database Programming:


1. Import database specific module
Eg: import cx_Oracle

2. Establish Connection between Python Program and database.


We can create this Connection object by using connect() function of the module.
con = cx_Oracle.connect(datbase information)

Eg: con=cx_Oracle.connect('scott/tiger@localhost')

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

i) execute(sqlquery)  To execute a single sql query


ii) executescript(sqlqueries)  To execute a string of sql queries seperated by semi-colon ';'
iii) 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)

commit()  Saves the changes to the database


rollback()  rolls all temporary changes back

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)

7. close the resources


After completing our operations it is highly recommended to close the resources in the reverse
order of their opening by using close() methods.

cursor.close()
con.close()

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

These methods won't be changed from database to database and same for all databases.

Working with Oracle Database:


From Python Program if we want to communicate with any database,some translator must be
required to translate Python calls into Database specific calls and Database specific calls into
Python calls.This translator is nothing but Driver/Connector.

Diagram

For Oracle database the name of driver needed is cx_Oracle.


cx_Oracle is a Python extension module that enables access to Oracle Database.It can be used for
both Python2 and Python3. It can work with any version of Oracle database like 9,10,11 and 12.

Installing cx_Oracle:
From Normal Command Prompt (But not from Python console)execute the following command

D:\python_classes>pip install cx_Oracle

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

How to Test Installation:


From python console execute the following command:

>>> help("modules")

In the output we can see cx_Oracle

....
_multiprocessing crypt ntpath timeit
_opcode csv nturl2path tkinter
_operator csvr numbers token
_osx_support csvw opcode tokenize
_overlapped ctypes operator trace
_pickle curses optparse traceback
_pydecimal custexcept os tracemalloc
_pyio cx_Oracle parser try
_random data pathlib tty
_sha1 datetime pdb turtle
_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 Digitmath plistlib uu
_stat easy_install polymorph uuid
.....

App1: Program to connect with Oracle database and print its version.
1) import cx_Oracle
2) con=cx_Oracle.connect('scott/tiger@localhost')
3) print(con.version)
4) con.close()

Output:
D:\python_classes>py db1.py
11.2.0.2.0

App2: Write a Program to create employees table in the oracle database :


employees(eno,ename,esal,eaddr)

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

12) if cursor:
11) finally:
14) if con:
15) con.close()
13)cursor.close()

App3: Write a program to drop employees table from oracle database?


1)import cx_Oracle
2)try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5)cursor.execute("drop table employees")
6) print("Table dropped successfully")

7)except cx_Oracle.DatabaseError
8) if con: as e:

10) print("There is a problem with sql",e)


9)con.rollback()
12) if cursor:
11) finally:
14) if con:
15) con.close()
13)cursor.close()

App3: Write a program to insert a single row in the employees table.


1)import cx_Oracle
2)try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5)cursor.execute("insert into employees values(100,'Digit',1000,'Hyd')")
6) con.commit()

7)print("Record
8)except Inserted Successfully")
cx_Oracle.DatabaseError as e:

10) con.rollback()
9)if con:
12) finally:
11)print("There is a problem with sql",e)
14) cursor.close()

13)if cursor: con.close()


16)

Note:15)if
Whilecon:
performing DML Operations (insert|update|delte), compulsory we have to use
commit() method,then only the results will be reflected in the database.

App4: Write a program to insert multiple rows in the employees table by


using executemany() method.
1)import cx_Oracle
2)try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5)sql="insert into employees values(:eno,:ename,:esal,:eaddr)" 7)(300,'Chinny',3000,'Hyd'),
9)cursor.executemany(sql,records)
6) records=[(200,'Sunny',2000,'Mumbai'),

8) (400,'Bunny',4000,'Hyd')]
11)print("Records Inserted Successfully")
10) con.commit()
13)if con:
12) except cx_Oracle.DatabaseError as e:

14) con.rollback()
15)print("There is a problem with sql",e)

16) finally:
17)if cursor:
18) cursor.close()

19)if con:
20) con.close()

App5: Write a program to insert multiple rows in the employees table with
dynamic input from the keyboard?
1)import cx_Oracle
2)try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5)while True:
6) eno=int(input("Enter Employee Number:"))
7) ename=input("Enter Employee Name:")
8) esal=float(input("Enter Employee Salary:"))
9)eaddr=input("Enter Employee Address:")
10) sql="insert into employees values(%d,'%s',%f,'%s')"

11)cursor.execute(sql
12) %(eno,ename,esal,eaddr))
print("Record Inserted Successfully")

14) if option=="No":
13)option=input("Do you want to insert one more record[Yes|No] :")
16) break
15)con.commit()
18) if con:

20)
17) print("There is a problem
except cx_Oracle.DatabaseError with sql :",e)
as e:

22) if cursor:
19)con.rollback()
24) if con:
25) con.close()
21) finally:

23)cursor.close()
App6: Write a program to update employee salaries with increment for the
certain range with dynamic input.

Eg: Increment all employee salaries by 500 whose salary < 5000
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
8) employees set esal=esal+%f
cursor.execute(sql where esal<%f"
%(increment,salrange))

10) con.commit()
9)print("Records Updated Successfully")
12) if con:
11) except cx_Oracle.DatabaseError as e:
14) print("There is a problem with sql :",e)

16) if cursor:
13)con.rollback()

18) if con:
15)
19) finally: con.close()

17)cursor.close()

App7: 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
8) %(cutoffsalary))
print("Records Deleted Successfully")

10) except cx_Oracle.DatabaseError as e:


9)con.commit()
12) con.rollback()
11)if con:
14) finally:

16) cursor.close()
13)print("There is a problem with sql :",e)

18) con.close()
15)if cursor:

17)if con:

App8: Write a program to select all employees info by using fetchone()


method?
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) row=cursor.fetchone()

7)while
8) row is not None:
print(row)

10) except cx_Oracle.DatabaseError as e:


9)row=cursor.fetchone()
12) con.rollback()
11)if con:
14) finally:

16) cursor.close()
13)print("There is a problem with sql :",e)

18) con.close()
15)if cursor:

17)if con:
App9: Write a program to select all employees info by using fetchall()
method?
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) data=cursor.fetchall()

7)for row in data:


8) print("Employee Number:",row[0])

10) print("Employee Salary:",row[2])


9)print("Employee Name:",row[1])
12) print()
11)print("Employee Address:",row[3])
14) except cx_Oracle.DatabaseError as e:

16)
13)print() con.rollback()

18) finally:
15)if con:
20) cursor.close()
17)print("There is a problem with sql :",e)
22) con.close()

19)if cursor:

21)if con:

App10: Write a program to select employees info by using fetchmany()


method and the required number of rows will be provided as dynamic input?
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:

10) except cx_Oracle.DatabaseError as e:


9)print(row)
12) con.rollback()
11)if con:
14) finally:

16) cursor.close()
13)print("There is a problem with sql :",e)

18) con.close()
15)if cursor:

17)if con:

Output:
D:\python_classes>py test.py
Enter the number of required rows:3
(100, 'Digit', 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, 'Digit', 1500.0, 'Hyd')
(200, 'Sunny', 2500.0, 'Mumbai')
(300, 'Chinny', 3500.0, 'Hyd')
(400, 'Bunny', 4500.0, 'Hyd')

Working with Mysql database:


Current version: 5.7.19
Vendor: SUN Micro Systems/Oracle Corporation
Open Source and Freeware
Default Port: 3306
Default user: root

Note: In MySQL, everything we have to work with our own databases, which are also known as
Logical Databases.

The following are 4 default databases available in mysql.


1. information_schema
2. mysql
3. performance_schema
4. test

Diagram

In the above diagram only one physical database is available and 4 logical databases are available.

Commonly used commands in MySql:


1. To know available databases:
mysql> show databases;

2. To create our own logical database


mysql> create database Digitdb;

3. To drop our own database:


mysql> drop database Digitdb;

4. To use a particular logical database


mysql> use Digitdb; OR mysql> connect Digitdb;

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,'Digit',1000,'Hyd'); insert
into employees values(200,'Ravi',2000,'Mumbai');

In MySQL instead of single quotes we can use double quotes also.

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.
Diagram

We have to download connector seperately from mysql database.

https://dev.mysql.com/downloads/connector/python/2.1.html

How to check installation:


From python console we have to use
help("modules")

In the list of modules,compulsory mysql should be there.

Note: In the case of Python3.4 we have to set PATH and PYTHONPATH explicitly PATH=C:\

Python34
PYTHONPATH=C:\Python34\Lib\site-packages

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='Digitdb',user='root',password='root')
4) cursor=con.cursor()
5)cursor.execute("create table employees(eno int(5) primary key,ename varchar(10),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'),

12) cursor.executemany(sql,records)
11)(300,'Kohli',3000,'Delhi')]

14) print("Records Inserted Successfully...")


13)con.commit() 15)
16) cursor.execute("select * from employees")
17)data=cursor.fetchall()

18) for row in data:


19)print("Employee Number:",row[0])
20) print("Employee Name:",row[1])
21)print("Employee Salary:",row[2])
22) print("Employee Address:",row[3])

24)
23)print() print()

26) if con:
25) except mysql.connector.DatabaseError as e:
28) print("There is a problem with sql :",e)

27)con.rollback()
30) if cursor:

32) if con:
29) finally:

31)cursor.close()

33)con.close()

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='Digitdb',user='root',password='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:
con=cx_Oracle.connect('scott/tiger@localhost')
23)
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")
29) except cx_Oracle.DatabaseError as e:
30) if con:
31) con.rollback()
32) print("There is a problem with sql",e)
33) finally:
34) if cursor:

35)cursor.close()
36) if con:
37) con.close()

https://dev.mysql.com/downloads/connector/python/2.1.html

1)create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2),eaddr varchar(10));


2)
3) insert into employees values(100,'Digit',1000,'Hyd');
4) insert into employees values(200,'Ravi',2000,'Mumbai');
5) insert into employees values(300,'Shiva',3000,'Hyd');

You might also like