0% found this document useful (0 votes)
7 views22 pages

SYIT Python 1

The document explains various Python string methods including len(), upper(), lower(), capitalize(), and swapcase(), emphasizing that these methods return new strings without altering the original. It also covers string slicing, indexing (both positive and negative), and the immutability of strings. Additionally, it introduces tuples, their creation, and concatenation operations, alongside a brief overview of the random module in Python for generating random numbers.

Uploaded by

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

SYIT Python 1

The document explains various Python string methods including len(), upper(), lower(), capitalize(), and swapcase(), emphasizing that these methods return new strings without altering the original. It also covers string slicing, indexing (both positive and negative), and the immutability of strings. Additionally, it introduces tuples, their creation, and concatenation operations, alongside a brief overview of the random module in Python for generating random numbers.

Uploaded by

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

UNIT II

Q.Explain following five methods of a string:


i)len() ii) upper() iii) lower() iv) capitalize() v) swapcase()
OR
Explain any five methods of a python string.

Answer:
Python String Methods
Python string methods is a collection of in-built Python functions that operates on lists.
Note: Every string method in Python does not change the original string instead returns a new string
with the changed attributes.
Python string is a sequence of Unicode characters that is enclosed in quotation marks. In this article,
we will discuss the in-built string functions i.e. the functions provided by Python to operate on
strings.
Case Changing of Python String Methods
The below Python functions are used to change the case of the strings. Let’s look at some Python
string methods with examples:
• lower(): Converts all uppercase characters in a string into lowercase
• upper(): Converts all lowercase characters in a string into uppercase
• title(): Convert string to title case
• swapcase(): Swap the cases of all characters in a string
• capitalize(): Convert the first character of a string to uppercase
Example: Changing the case of Python String Methods
Python
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print(text.upper())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print(text.lower())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print(text.title())

# swaps the case of all characters in the string


# upper case character to lowercase and viceversa
print("\nConverted String:")
print(text.swapcase())
# convert the first character of a string to uppercase
print("\nConverted String:")
print(text.capitalize())

# original string never changes


print("\nOriginal String")
print(text)

Output
Converted String:
GEEKS FOR GEEKS

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Converted String:
GEEkS fOR GEeKs

Original String
geeKs For geEkS

Q.Explain string slicing with an example.


Python Slicing Strings
Python String slicing is a way of creating a sub-string from a given string. In this process, we extract a
portion or piece of a string. Usually, we use the slice operator "[ : ]" to perform slicing on a Python
String. Before proceeding with string slicing let's understand string indexing.
In Python, a string is an ordered sequence of Unicode characters. Each character in the string has a
unique index in the sequence. The index starts with 0. First character in the string has its positional
index 0. The index keeps incrementing towards the end of string.
If a string variable is declared as var="HELLO PYTHON", index of each character in the string is as
follows −
Python String Indexing
Python allows you to access any individual character from the string by its index. In this case, 0 is the
lower bound and 11 is the upper bound of the string. So, var[0] returns H, var[6] returns P. If the
index in square brackets exceeds the upper bound, Python raises IndexError.
Example
In the below example, we accessing the characters of a string through index.
Open Compiler
var = "HELLO PYTHON"
print(var[0])
print(var[7])
print(var[11])
print(var[12])
On running the code, it will produce the following output −
H
Y
N
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
IndexError: string index out of range

Python String Negative & Positive Indexing


One of the unique features of Python sequence types (and therefore a string object) is that it has a
negative indexing scheme also. In the example above, a positive indexing scheme is used where the
index increments from left to right. In case of negative indexing, the character at the end has -1 index
and the index decrements from right to left, as a result the first character H has -12 index.

Example
Let us use negative indexing to fetch N, Y, and H characters.
Open Compiler
var = "HELLO PYTHON"
print(var[-1])
print(var[-5])
print(var[-12])
On executing the above code, it will give the following result −
N
Y
H
We can therefore use positive or negative index to retrieve a character from the string.
In Python, string is an immutable object. The object is immutable if it cannot be modified in-place,
once stored in a certain memory location. You can retrieve any character from the string with the
help of its index, but you cannot replace it with another character.
Example
In the following example, character Y is at index 7 in HELLO PYTHON. Try to replace Y with y and see
what happens.
Open Compiler
var="HELLO PYTHON"
var[7]="y"
print (var)
It will produce the following output −
Traceback (most recent call last):
File "C:\Users\users\example.py", line 2, in <module>
var[7]="y"
~~~^^^
TypeError: 'str' object does not support item assignment
The TypeError is because the string is immutable.

Python String Slicing


Python defines ":" as string slicing operator. It returns a substring from the original string. Its general
usage is as follows −
substr=var[x:y]
The ":" operator needs two integer operands (both of which may be omitted, as we shall see in
subsequent examples). The first operand x is the index of the first character of the desired slice. The
second operand y is the index of the character next to the last in the desired string. So var(x:y]
separates characters from xth position to (y-1)th position from the original string.
Example
Open Compiler
var="HELLO PYTHON"

print ("var:",var)
print ("var[3:8]:", var[3:8])
It will produce the following output −
var: HELLO PYTHON
var[3:8]: LO PY

Python String Slicing With Negative Indexing


Like positive indexes, negative indexes can also be used for slicing.
Example
The below example shows how to slice a string using negative indexes.
Open Compiler
var="HELLO PYTHON"
print ("var:",var)
print ("var[3:8]:", var[3:8])
print ("var[-9:-4]:", var[-9:-4])
It will produce the following output −
var: HELLO PYTHON
var[3:8]: LO PY
var[-9:-4]: LO PY

Default Values of Indexes with String Slicing


Both the operands for Python's Slice operator are optional. The first operand defaults to zero, which
means if we do not give the first operand, the slice starts of character at 0th index, i.e. the first
character. It slices the leftmost substring up to "y-1" characters.
Example
In this example, we are performing slice operation using default values.
Open Compiler
var="HELLO PYTHON"
print ("var:",var)
print ("var[0:5]:", var[0:5])
print ("var[:5]:", var[:5])
It will produce the following output −
var: HELLO PYTHON
var[0:5]: HELLO
var[:5]: HELLO
Example
Similarly, y operand is also optional. By default, it is "-1", which means the string will be sliced from
the xth position up to the end of string.
Open Compiler
var="HELLO PYTHON"
print ("var:",var)
print ("var[6:12]:", var[6:12])
print ("var[6:]:", var[6:])
It will produce the following output −
var: HELLO PYTHON
var[6:12]: PYTHON
var[6:]: PYTHON
Example
Naturally, if both the operands are not used, the slice will be equal to the original string. That's
because "x" is 0, and "y" is the last index+1 (or -1) by default.
Open Compiler
var="HELLO PYTHON"
print ("var:",var)
print ("var[0:12]:", var[0:12])
print ("var[:]:", var[:])
It will produce the following output −
var: HELLO PYTHON
var[0:12]: HELLO PYTHON
var[:]: HELLO PYTHON
Example
The left operand must be smaller than the operand on right, for getting a substring of the original
string. Python doesn't raise any error, if the left operand is greater, but returns a null string.
Open Compiler
var="HELLO PYTHON"
print ("var:",var)
print ("var[-1:7]:", var[-1:7])
print ("var[7:0]:", var[7:0])
It will produce the following output −
var: HELLO PYTHON
var[-1:7]:
var[7:0]:

Return Type of String Slicing


Slicing returns a new string. You can very well perform string operations like concatenation, or slicing
on the sliced string.
Example
Open Compiler
var="HELLO PYTHON"

print ("var:",var)
print ("var[:6][:2]:", var[:6][:2])

var1=var[:6]
print ("slice:", var1)
print ("var1[:2]:", var1[:2])
It will produce the following output −
var: HELLO PYTHON
var[:6][:2]: HE
slice: HELLO
var1[:2]: HE

Q.Explain positive indexing and negative indexing of a string.


The Python string data type is a sequence made up of one or more individual characters that could
consist of letters, numbers, whitespace characters, or symbols. As the string is a sequence, it can be
accessed in the same ways that other sequence-based data types are, through indexing and slicing.
Indexing
Indexing means referring to an element of an iterable by its position within the iterable. Each of a
string’s characters corresponds to an index number and each character can be accessed using its
index number. We can access characters in a String in Two ways :
1. Accessing Characters by Positive Index Number
2. Accessing Characters by Negative Index Number
1. Accessing Characters by Positive Index Number: In this type of Indexing, we pass a Positive
index(which we want to access) in square brackets. The index number starts from index number 0
(which denotes the first character of a string).
Indexing in Python
Example 1 (Positive Indexing) :
python3

# declaring the string


str = "Geeks for Geeks !"

# accessing the character of str at 0th index


print(str[0])

# accessing the character of str at 6th index


print(str[6])

# accessing the character of str at 10th index


print(str[10])

Output
G
f
G
2. Accessing Characters by Negative Index Number: In this type of Indexing, we pass the Negative
index(which we want to access) in square brackets. Here the index number starts from index number
-1 (which denotes the last character of a string). Example 2 (Negative Indexing) :
python3

# declaring the string


str = "Geeks for Geeks !"

# accessing the character of str at last index


print(str[-1])

# accessing the character of str at 5th index from the last


print(str[-5])

# accessing the character of str at 10th index from the last


print(str[-10])

Output
!
e
o
UNIT III
How to create tuple in python? Explain concatenation operation on tuple with an example.
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Creating a Tuple
In Python Programming, tuples are created by placing a sequence of values separated by ‘comma’
with or without the use of parentheses for grouping the data sequence.
Python Program to Demonstrate the Addition of Elements in a Tuple.
Python
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple
# with the use of string
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

Output:
Initial empty Tuple:
()

Tuple with the use of String:


('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')

Concatenation of Tuples
Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done by the
use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple. Other
arithmetic operations do not apply on Tuples.
Note- Only the same datatypes can be combined with concatenation, an error arises if a list and a
tuple are combined.

Python
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'For', 'Geeks')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple


print("Tuple 1: ")
print(Tuple1)

# Printing Second Tuple


print("\nTuple2: ")
print(Tuple2)

# Printing Final Tuple


print("\nTuples after Concatenation: ")
print(Tuple3)
Output:
Tuple 1:
(0, 1, 2, 3)
Tuple2:
('Geeks', 'For', 'Geeks')
Tuples after Concatenation:
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
What is tuple ? How to create the tuple with one item and tuple with multiple items in python.
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Creating a Tuple
In Python Programming, tuples are created by placing a sequence of values separated by ‘comma’
with or without the use of parentheses for grouping the data sequence

Creating Python Tuples


Using Round Brackets
In Python, tuples are created by placing a sequence of values separated by commas within round
brackets ().
Example
# Creating a tuple with multiple items
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
Output
(1, 2, 3, 4, 5)
With One Item
Creating a tuple with a single item can be tricky because Python uses parentheses for grouping
expressions. You must include a comma after the item to indicate that you are making a tuple with
one item.
Example
# Creating a tuple with one item
single_item_tuple = (5,)
print(single_item_tuple)
Output
(5,)
If you forget the comma, Python interprets the parentheses as a regular expression grouping, not a
tuple.
Incorrect Example
# This is not a tuple
not_a_tuple = (5)
print(not_a_tuple)
Output
5
In this case, not_a_tuple is just an integer enclosed in parentheses, not a tuple.
UNIT IV
Q.Explain random module in python.
Python Random module
The Python Random module is a built-in module for generating random integers in Python.
These numbers occur randomly and does not follow any rules or instructuctions. We can
therefore use this module to generate random numbers, display a random item for a list or
string, and so on.

The random() Function


The random.random() function gives a float number that ranges from 0.0 to 1.0. There are no
parameters required for this function. This method returns the second random floating-point
value within [0.0 and 1] is returned.
Code
1. # Python program for generating random float number
2. import random
3. num=random.random()
4. print(num)
Output:
0.3232640977876686

The randint() Function


The random.randint() function generates a random integer from the range of numbers
supplied.
Code
1. # Python program for generating a random integer
2. import random
3. num = random.randint(1, 500)
4. print( num )
Output:
215

The randrange() Function


The random.randrange() function selects an item randomly from the given range defined by
the start, the stop, and the step parameters. By default, the start is set to 0. Likewise, the step
is set to 1 by default.
Code
1. # To generate value between a specific range
2. import random
3. num = random.randrange(1, 10)
4. print( num )
5. num = random.randrange(1, 10, 2)
6. print( num )
Output:
4
9
The choice() Function
The random.choice() function selects an item from a non-empty series at random. In the
given below program, we have defined a string, list and a set. And using the above choice()
method, random element is selected.
Code
1. # To select a random element
2. import random
3. random_s = random.choice(&#39;Random Module&#39;) #a string
4. print( random_s )
5. random_l = random.choice([23, 54, 765, 23, 45, 45]) #a list
6. print( random_l )
7. random_s = random.choice((12, 64, 23, 54, 34)) #a set
8. print( random_s )
Output:
M
765
54

The shuffle() Function


The random.shuffle() function shuffles the given list randomly.
Code
1. # To shuffle elements in the list
2. list1 = [34, 23, 65, 86, 23, 43]
3. random.shuffle( list1 )
4. print( list1 )
5. random.shuffle( list1 )
6. print( list1 )
Output:
[23, 43, 86, 65, 34, 23]
[65, 23, 86, 23, 34, 43]

Q.What is module? How to create and import module in python?


OR
Write a short note on importing a module in python.
In Python, a module is a self-contained Python file that contains Python statements and definitions,
like a file named GFG.py, can be considered as a module named GFG which can be imported with the
help of import statement. However, one might get confused about the difference between modules
and packages. A package is a collection of modules in directories that give structure and hierarchy to
the modules.
Advantages of modules –
• Reusability: Working with modules makes the code reusability a reality.
• Simplicity: Module focuses on a small proportion of the problem, rather than focusing on
the entire problem.
• Scoping: A separate namespace is defined by a module that helps to avoid collisions
between identifiers.
The import Module in Python
To use the functionality present in any module, you have to import it into your current program. You
need to use the import keyword along with the desired module name. When the interpreter comes
across an import statement, it imports the module to your current program. You can use the
functions inside a module by using a dot (.) operator along with the module name. First, let's see
how to use the standard library modules. In the example below, the math module is imported into
the program so that you can use the sqrt() function.

import math
num = 4
print(math.sqrt(num)) #Use dot operator to access sqrt() inside module "math"

Output:
2

This code imports the math module using the import keyword and assigns the value of 4 to the
variable num. It then uses the sqrt() function from the math module to calculate the square root of
num and prints the result to the console using the print() function. The sqrt() function is accessed
using the dot operator (.) to indicate that it is a function within the math module. The math module
provides access to a variety of mathematical functions and constants.

Creating Modules in Python


Now that you have learned how to import a module in your program, it is time to write your own,
and use it in another program. Writing a module is just like writing any other Python file. Let's start
by writing a function to add/subtract two numbers in a file calculation.py
calculation.py
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)

This code defines two functions, add and sub.


The add function takes two arguments, x and y, and returns their sum using the + operator.
The sub function also takes two arguments, x and y, and returns their difference using the - operator.
These functions can be called later in the code to perform addition and subtraction operations on
any two numbers.

If you try to execute this script on the command line, nothing will happen because you have not
instructed the program to do anything. Create another Python script in the same directory with the
name module_test.py and write the following code into it.

import calculation #Importing calculation module


print(calculation.add(1,2)) #Calling function defined in add module.

If you execute module_test.py, you will see "3" as output. When the interpreter came across
the import statement, it imported the calculation module in your code and then by using the dot
operator, you were able to access the add() function.
This code imports a module named "calculation" and then calls a function named "add" from that
module. The "add" function takes two arguments, 1 and 2, and returns their sum, which is then
printed to the console using the "print" function.
The "import" statement is a Python keyword used to import modules into a program. In this case, the
"calculation" module is being imported. The "print" function is used to output the result of the "add"
function to the console.

Additional Ways to Import Modules in Python


from ... import statement
The from..import statement allows you to import specific functions/variables from a module instead
of importing everything. In the previous example, when you
imported calculation into module_test.py both the add() and sub() functions were imported. But
what if you only needed the add() function in your code? Here is an example to illustrate the use
of from..import

from calculation import add


print(add(1,2))

This code imports the add function from a module called calculation and then calls the add function
with the arguments 1 and 2. The add function likely performs addition on the two arguments and
returns the result. The print statement then outputs the result of the add function call, which should
be 3.
UNIT V
1.How to create entry widget? Explain with its options(parameters).
Tkinter Entry
The Entry widget is used to accept single-line text strings from a user.
• If you want to display multiple lines of text that can be edited, then you should use the Text
widget.
• If you want to display one or more lines of text that cannot be modified by the user, then you
should use the Label widget.
Syntax
Here is the simple syntax to create this widget −
w = Entry( master, option, ... )

Parameters
• master − This represents the parent window.
• options − Here is the list of most commonly used options for this widget. These options can
be used as key-value pairs separated by commas.
Sr.No. Option & Description

Bg
1
The normal background color displayed behind the label and indicator.

Bd
2
The size of the border around the indicator. Default is 2 pixels.

Command
3
A procedure to be called every time the user changes the state of this checkbutton.

Cursor
4 If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that
pattern when it is over the checkbutton.

Font
5
The font used for the text.

Fg
6
The color used to render the text.

Justify
8 If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or
RIGHT.

Relief
9 With the default value, relief=FLAT, the checkbutton does not stand out from its background. You
may set this option to any of the other styles.

Selectbackground
10
The background color to use displaying selected text.
Selectborderwidth
11
The width of the border to use around selected text. The default is one pixel.

Selectforeground
12
The foreground (text) color of selected text.

Show
13 Normally, the characters that the user types appear in the entry. To make a .password. entry that
echoes each character as an asterisk, set show="*".

State
14 The default is state=NORMAL, but you can use state=DISABLED to gray out the control and make
it unresponsive. If the cursor is currently over the checkbutton, the state is ACTIVE.

Textvariable
15 In order to be able to retrieve the current text from your entry widget, you must set this option to
an instance of the StringVar class.

Width
The default width of a checkbutton is determined by the size of the displayed image or text. You
16
can set this option to a number of characters and the checkbutton will always have room for that
many characters.

Example
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()

When the above code is executed, it produces the following result −


2. How to create Button widget? Explain with its options(parameters).
Tkinter Label
This widget implements a display box where you can place text or images. The text displayed by this
widget can be updated at any time you want.
It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text
across multiple lines.
Syntax
Here is the simple syntax to create this widget −
w = Label ( master, option, ... )

Parameters
• master − This represents the parent window.
• options − Here is the list of most commonly used options for this widget. These options can
be used as key-value pairs separated by commas.
Sr.No. Options & Description

Anchor
1 This options controls where the text is positioned if the widget has more space than the text
needs. The default is anchor=CENTER, which centers the text in the available space.

Bg
2
The normal background color displayed behind the label and indicator.

Bitmap
3
Set this option equal to a bitmap or image object and the label will display that graphic.

Bd
4
The size of the border around the indicator. Default is 2 pixels.

Cursor
5 If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that
pattern when it is over the checkbutton.

Font
6 If you are displaying text in this label (with the text or textvariable option, the font option
specifies in what font that text will be displayed.

Fg
If you are displaying text or a bitmap in this label, this option specifies the color of the text. If you
7
are displaying a bitmap, this is the color that will appear at the position of the 1-bits in the
bitmap.

height
8
The vertical dimension of the new frame.

image
9
To display a static image in the label widget, set this option to an image object.
justify
10 Specifies how multiple lines of text will be aligned with respect to each other: LEFT for flush left,
CENTER for centered (the default), or RIGHT for right-justified.

padx
11
Extra space added to the left and right of the text within the widget. Default is 1.

pady
12
Extra space added above and below the text within the widget. Default is 1.

relief
13 Specifies the appearance of a decorative border around the label. The default is FLAT; for other
values.

text
14 To display one or more lines of text in a label widget, set this option to a string containing the
text. Internal newlines ("\n") will force a line break.

textvariable
15 To slave the text displayed in a label widget to a control variable of class StringVar, set this option
to that variable.

underline
16 You can display an underline (_) below the nth letter of the text, counting from 0, by setting this
option to n. The default is underline=- 1, which means no underlining.

width
17 Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit
its contents.

wraplength
18 You can limit the number of characters in each line by setting this option to the desired number.
The default value, 0, means that lines will be broken only at newlines.

Example
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()

When the above code is executed, it produces the following result −


What is commit() and rollback() operations used in python?

Commit & RollBack Operation in Python


Python’s commit() method and rollback() method are among the various methods used for making
database transactions. Database transactions are necessary as they ensure the atomicity,
consistency, isolation and durability of the database.
In this article, we will focus on the use of commit() and rollback() method in detail.

1. The commit() method:


The commit() method is used to make sure the changes made to the database are consistent. It
basically provides the database confirmation regarding the changes made by a user or an application
in the database.
Syntax:
comm.commit() #comm refers to the database connection object
For a better understanding of the concept look into the code below followed by the code
explanation. The below demonstration of the commit() method is performed on a MySQL database.
Example:
Program to update the age of a student named Rishi Kumar and commit it to the database.
MySQL Table in use:

# Python program to demonstrate


# commit() method
import mysql.connector

# Connecting to the Database


mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
)
cs = mydb.cursor()
# drop clause
statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"

cs.execute(statement)

# commit changes to the database


mydb.commit()

# Disconnecting from the database


mydb.close()
Output:

2. The rollback() method:


The rollback() method is used to revert the last changes made to the database. If a condition arises
where one is not satisfied with the changes made to the database or a database transaction fails, the
rollback() method can be used to retrieve the original data that was changed through the commit()
method.
Syntax:
comm.rollback() #comm refers to the database connection object
The below code shows the use of rollback() method to revert changes if a database transaction fails:

# Python program to demonstrate


# rollback() method

import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode

try:
# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
)

cs = mydb.cursor()

# drop clause
statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"

cs.execute(statement)

# commit changes to the database


mydb.commit()

# update successful message


print("Database Updated !")

except mysql.connector.Error as error :

# update failed message as an error


print("Database Update Failed !: {}".format(error))

# reverting changes because of exception


mydb.rollback()

# Disconnecting from the database


mydb.close()

Output:
If the database transaction is successful the output will be,
Database Updated!

If the database transaction fails the output is an error raised as,


Database Update Failed!

You might also like