Sending Email
Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending e-mail and routing e-mail between mail servers.
Python provides smtplib module which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.Syntax:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters:- host: This is the host running your SMTP server. You can specifiy IP address of the host or a domain name. This is optional argument.
- port: If you are providing host argument then you need to specifiy a port where SMTP server is listening. Usually this port would be 25.
- local_hostname: If your SMTP server is running on your local machine then you can specify just localhost as of this option.
It takes three parameters:- The sender - A string with the address of the sender.
- The receivers - A list of strings, one for each recipient.
- The message - A message as a string formatted as specified in the various RFCs.
Example
#!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person < from@fromdomain.com >
To: To Person < to@todomain.com >
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Auto AdSense
Saturday, 24 January 2015
Python Programs - Sending Email using SMTP
Python Programs - Regular Expressions - Search Function
- #!/usr/bin/python
import re
line = "Cats are smarter than dogs";
matchObj = re.search( r'(.*) are(\.*)', line, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!" Output
matchObj.group(): Cats are
matchObj.group(1) : Cats
matchObj.group(2) :
Python Programs - Regular Expressions - Match Function
- #!/usr/bin/python
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'(.*) are(\.*)', line, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!" Output
matchObj.group(): Cats are
matchObj.group(1) : Cats
matchObj.group(2) :
Python Tuples
Accessing Values in Tuples:
#!/usr/bin/python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]Output
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]Updating Tuples:
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;Output
(12, 34.56, 'abc', 'xyz')Delete Tuple Elements:
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : "
print tup;Output
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in < module >
print tup;
NameError: name 'tup' is not definedNo Enclosing Delimiters:
#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;
print var;Output
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
Python Strings
Accessing Values in Strings:
#!/usr/bin/python
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]Output
var1[0]: H
var2[1:5]: ythoUpdating Strings:
#!/usr/bin/python
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'Output
Updated String :- Hello PythonString Formatting Operator:
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)Output
My name is Zara and weight is 21 kg!Triple Quotes:
#!/usr/bin/python
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str;Output
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.Raw String:
#!/usr/bin/python
print 'C:\\nowhere'Output
C:\nowhereUnicode String:
#!/usr/bin/python
print u'Hello, world!'Output
Hello, world!
Python Lists
Accessing Values in Lists:
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]Output
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]Updating Lists:
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2];
list[2] = 2001;
print "New value available at index 2 : "
print list[2];Output
Value available at index 2 :
1997
New value available at index 2 :
2001Delete List Elements:
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;Output
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Python Files I/O
Reading Keyboard Input:
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are:raw_input
input
The raw_input Function:
#!/usr/bin/python
str = raw_input("Enter your input: ");
print "Received input is : ", strOutput
Enter your input: Hello Python
Received input is : Hello PythonThe input Function:
#!/usr/bin/python
str = input("Enter your input: ");
print "Received input is : ", strOutput
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
Opening and Closing Files:
Syntax:
file object = open(file_name [, access_mode][, buffering])
Here is paramters detail:- file_name: The file_name argument is a string value that contains the name of the file that you want to access.
- access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r)
- buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
The file object atrributes:
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspaceOutput
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0The close() Method:
Syntax:
fileObject.close();
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()Output
Name of the file: foo.txtReading and Writing Files:
The write() Method:
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string:Syntax:
fileObject.write(string);
Here passed parameter is the content to be written into the opend file.
Example:
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content
Python is a great language.
Yeah its great!!The read() Method:
Syntax:
fileObject.read([count]);
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This would produce following result:
Read String is : Python is
File Positions:
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
This would produce following result:
Read String is : Python is
Current file position : 10
Again read String is : Python isRenaming and Deleting Files:
The rename() Method:
The rename() method takes two arguments, the current filename and the new filename.Syntax:
os.rename(current_file_name, new_file_name)Example:
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )The delete() Method:
Syntax:
os.delete(file_name)Example:
Following is the example to delete an existing file test2.txt:
#!/usr/bin/python
import os
# Delete file test2.txt
os.delete("text2.txt")
Directories in Python:
The mkdir() Method:
Syntax:
os.mkdir("newdir")Example:
Following is the example to create a directory test in the current directory:
#!/usr/bin/python
import os
# Create a directory "test"
os.mkdir("test")The chdir() Method:
Syntax:
os.chdir("newdir")Example:
Following is the example to go into "/home/newdir" directory:
#!/usr/bin/python
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")The getcwd() Method:
Syntax:
os.getcwd()Example:
Following is the example to give current directory:
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()The rmdir() Method:
Syntax:
os.rmdir('dirname')Example:
Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory otherwise it would search for that directory in the current directory.
#!/usr/bin/python
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
Python Dictionary
Accessing Values in Dictionary:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];Output
dict['Name']: Zara
dict['Age']: 7Updating Dictionary:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];Output
dict['Age']: 8
dict['School']: DPS SchoolDelete Dictionary Elements:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];Output
This will produce following result. Note an exception raised, this is because after del dict dictionary does not exist any more:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in < module >
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptableProperties of Dictionary Keys:
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Following is a simple example:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
When the above code is executed, it produces following result:
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example:
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
When the above code is executed, it produces following result:
Traceback (most recent call last):
File "test.py", line 3, in < module >
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable
Python Date/Time
What is Tick?
Python's time and calendar modules help track dates and times.
Time intervals are floating-point numbers in units of seconds.
Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch).Example:
#!/usr/bin/python
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
This would produce a result something as follows:
Number of ticks since 12:00am, January 1, 1970: 7186862.73399Getting current time -:
#!/usr/bin/python
localtime = time.localtime(time.time())
print "Local current time :", localtimeOutput
Local current time : (2008, 5, 15, 12, 55, 32, 0, 136, 1)Getting formatted time -:
#!/usr/bin/python
import time;
localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtimeOutput
Local current time : Tue Jan 13 10:17:09 2009Getting calendar for a month -:
#!/usr/bin/python
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal;Output
Here is the calendar:
January 2008
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Python Object Oriented - Overriding Methods
- #!/usr/bin/python
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.myMethod() # child calls overridden method Output
Calling child method
Python Object Oriented - Overloading Operators
- #!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2 Output
Vector(7,8)
Python Object Oriented - Data Hiding
- #!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount Output
1
2
Traceback (most recent call last):
File "test.py", line 12, in < module >
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'- Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it would work for you:
.........................
print counter._JustCounter__secretCountOutput
1
2
2
Python Object Oriented - Class Inheritance
- #!/usr/bin/python
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method Output
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200- Similar way you can drive a class from multiple parent classes as follows:
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
Python Object Oriented - Classes
Creating Classes:
The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows:
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string which can be access via ClassName.__doc__.
The class_suite consists of all the component statements, defining class members, data attributes, and functions.Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salaryCreating instance objects:
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)Accessing attributes:
You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Python Programs - Multithreading - Synchronizing Threads:
Synchronization
#!/usr/bin/python
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
self.threadID = threadID
self.name = name
self.counter = counter
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"Output
Starting Thread-1
Starting Thread-2
Thread01: Thu Jan 22 16:04:38 2009
Thread01: Thu Jan 22 16:04:39 2009
Thread01: Thu Jan 22 16:04:40 2009
Thread02: Thu Jan 22 16:04:42 2009
Thread02: Thu Jan 22 16:04:44 2009
Thread02: Thu Jan 22 16:04:46 2009
Exiting Main Thread
Python Multithreaded Programming
Starting a New Thread
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
passOutput
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
Python Program - Creating Thread using Threading Module
Threading Module
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
self.threadID = threadID
self.name = name
self.counter = counter
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.run()
while thread2.isAlive():
if not thread1.isAlive():
exitFlag = 1
pass
print "Exiting Main Thread"Output
Starting Thread-2
Starting Thread-1
Thread-1: Thu Jan 22 15:53:05 2009
Thread-2: Thu Jan 22 15:53:06 2009
Thread-1: Thu Jan 22 15:53:06 2009
Thread-1: Thu Jan 22 15:53:07 2009
Thread-2: Thu Jan 22 15:53:08 2009
Thread-1: Thu Jan 22 15:53:08 2009
Thread-1: Thu Jan 22 15:53:09 2009
Exiting Thread-1
Thread-2: Thu Jan 22 15:53:10 2009
Thread-2: Thu Jan 22 15:53:12 2009
Thread-2: Thu Jan 22 15:53:14 2009
Exiting Thread-2
Exiting Main Thread
Python Functions
- def functionname( parameters ):
"function_docstring"
function_suite
return [expression]Example
def printme( str ):
"This prints a passed string into this function"
print str
return
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function"); Output
I'm first call to user defined function!
Again second call to the same functionPass by reference vs value:
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylistOutput
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]- There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written.
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist Output
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Python Programs - Function Arguments
- You can call a function by using the following types of formal arguments::
Required arguments
Keyword arguments
Default arguments
Variable-length arguments Required arguments:
To call the function printme() you definitely need to pass one argument otherwise it would give a syntax error as follows:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme();Output
Traceback (most recent call last):
File "test.py", line 11, in < module >
printme();
TypeError: printme() takes exactly 1 argument (0 given)Keyword arguments:
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme( str = "My string");Output
My stringDefault arguments:
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name;
print "Age ", age;
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );Output
Name: miki
Age 50
Name: miki
Age 35Variable-length arguments:
Syntax:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
Example:
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );Output
Output is:
10
Output is:
70
60
50
Python Programs - Database - Update Operation:
Update Table
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
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()
Python Program - Database - READ Operation
READ Operation
READ Operation on any databasse means to fetch some useful information from the database.
Once our database connection is established, we are ready to make a query into this database.
We can use either fetchone() method to fetch single record or fetchall method to fetech multiple values from a database table.- fetchone(): This method fetches the next row of a query result set.
A result set is an object that is returned when a cursor object is used to query a table. - fetchall(): This method fetches all the rows in a result set.
If some rows have already been extracted from the result set, the fetchall() method retrieves the remaining rows from the result set. - rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method.
- fetchone(): This method fetches the next row of a query result set.
Example:
Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000.
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.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()
This will produce following result:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
Python Program - Database - Performing Transactions:
Transaction
Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties:- Atomicity: Either a transaction completes or nothing happens at all.
- Consistency: A transaction must start in a consistent state and leave the system is a consistent state.
- Isolaion: Intermediate results of a transaction are not visible outside the current transaction.
- Durability: Once a transaction was committed, the effects are persistent, even after a system failure.
- The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
Example:
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
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()COMMIT Operation:
Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted back.Example
db.commit()ROLLBACK Operation:
If you are not satisfied with one or more of the changes and you want to revert back those changes completely then use rollback method.Example
db.rollback()Disconnecting Database:
To disconnect Database connection, use close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.
However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.
Subscribe to:
Posts (Atom)