0% found this document useful (0 votes)
36 views

Chapter 5-1

This document discusses tuples in Python and connecting Python to databases like MySQL. It defines what a tuple is in Python and how they are created and accessed. Tuples are immutable sequences of objects like lists but cannot be changed once created. The document also covers tuple operations, built-in functions, and when to use tuples over lists. Finally, it discusses how to connect a Python application to MySQL by installing the mysql-connector module and performing operations like importing it and connecting to a database.

Uploaded by

payalrana2507
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)
36 views

Chapter 5-1

This document discusses tuples in Python and connecting Python to databases like MySQL. It defines what a tuple is in Python and how they are created and accessed. Tuples are immutable sequences of objects like lists but cannot be changed once created. The document also covers tuple operations, built-in functions, and when to use tuples over lists. Finally, it discusses how to connect a Python application to MySQL by installing the mysql-connector module and performing operations like importing it and connecting to a database.

Uploaded by

payalrana2507
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/ 23

CHAPTER 5

Tuple and Database


Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to
lists since the value of the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple cannot be changed.
Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed with the small
() brackets. The parentheses are optional but it is good practice to use. A tuple can be defined
as follows.
1. T1 = (101, "Peter", 22)
2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4. print(type(T1))
5. print(type(T2))
6. print(type(T3))
Output:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Note: The tuple which is created without using parentheses is also known as tuple packing.
An empty tuple can be created as follows.
T4 = ()
Creating a tuple with single element is slightly different. We will need to put comma after the
element to declare the tuple.
1. tup1 = ("JavaTpoint")
2. print(type(tup1))
3. #Creating a tuple with single element
4. tup2 = ("JavaTpoint",)
5. print(type(tup2))
Output:
<class 'str'>
<class 'tuple'>
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using
their specific index value.
Consider the following example of tuple:

Compiled By : Mr. Vinod S Mahajan


Example - 1
1. tuple1 = (10, 20, 30, 40, 50, 60)
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %d"%(count, i))
6. count = count+1
Output:
(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
Example - 2
1. tuple1 = tuple(input("Enter the tuple elements ..."))
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %s"%(count, i))
6. count = count+1
Output:
Enter the tuple elements ...123456
('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using
their specific index value.

Compiled By : Mr. Vinod S Mahajan


Tuple indexing and slicing
The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from 0
and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator. Python also allows us to
use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.

Consider the following example:


1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])
Output:
1
2
3
tuple index out of range
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an element
outside of tuple that raised an IndexError.
1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])

Compiled By : Mr. Vinod S Mahajan


8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])
Output:
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)

Negative Indexing
The tuple element can also access by using negative indexing. The index of -1 denotes the
rightmost element and -2 to the second last item and so on.
The elements from left to right are traversed using the negative indexing. Consider the following
example:
1. tuple1 = (1, 2, 3, 4, 5)
2. print(tuple1[-1])
3. print(tuple1[-4])
4. print(tuple1[-3:-1])
5. print(tuple1[:-1])
6. print(tuple1[-2:])
Output:
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)

Deleting Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are immutable.
To delete an entire tuple, we can use the del keyword with the tuple name.
Consider the following example.
1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. print(tuple1)
Output:

Compiled By : Mr. Vinod S Mahajan


(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "tuple.py", line 4, in <module>
print(tuple1)
NameError: name 'tuple1' is not defined

Basic Tuple operations


The operators like concatenation (+), repetition (*), Membership (in) works in the same way as
they work with the list. Consider the following table for more detail.
Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.
Operator Description Example
Repetition The repetition operator enables the tuple T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4,
elements to be repeated multiple times. 5)
Concatenation It concatenates the tuple mentioned on T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8,
either side of the operator. 9)
Membership It returns true if a particular item exists in print (2 in T1) prints True.
the tuple otherwise false
Iteration The for loop is used to iterate over the tuple for i in T1:
elements. print(i)
Output
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5
Python Tuple inbuilt functions
SN Function Description
1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is greater than
tuple2 otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
Where use tuple?
Using tuple instead of list is used in the following scenario.

Compiled By : Mr. Vinod S Mahajan


1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be
changed.
2. Tuple can simulate a dictionary without keys. Consider the following nested structure, which
can be used as a dictionary.
1. [(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]

List vs. Tuple


SN List Tuple
1 The literal syntax of list is shown by the The literal syntax of the tuple is shown by
[]. the ().
2 The List is mutable. The tuple is immutable.
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality than The tuple provides less functionality than
a tuple. the list.
5 The list is used in the scenario in which The tuple is used in the cases where we
we need to store the simple collections need to store the read-only collections i.e.,
with no constraints where the value of the value of the items cannot be changed. It
the items can be changed. can be used as the key inside the dictionary.
6 The lists are less memory efficient than a The tuples are more memory efficient
tuple. because of its immutability.

MYSQL with Python


To build the real world applications, connecting with the databases is the necessity for the
programming languages. However, python allows us to connect our application to the databases like
MySQL, SQLite, MongoDB, and many others.

In this section of the tutorial, we will discuss Python - MySQL connectivity, and we will perform the
database operations in python. We will also cover the Python connectivity with the databases like
MongoDB and SQLite later in this tutorial.

Install mysql.connector

To connect the python application with the MySQL database, we must import the mysql.connector
module in the program.

The mysql.connector is not a built-in module that comes with the python installation. We need to
install it to get it working.

Execute the following command to install it using pip installer.

1. > python -m pip install mysql-connector


Or follow the following steps.

1. Click the link:

Compiled By : Mr. Vinod S Mahajan


https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b8660d09f91d8d5411
298bcacbd309f96/mysql-connector-python-8.0.13.tar.gz to download the source code.

2. Extract the archived file.

3. Open the terminal (CMD for windows) and change the present working directory to the source code
directory.

1. $ cd mysql-connector-python-8.0.13/
4. Run the file named setup.py with python (python3 in case you have also installed python 2) with
the parameter build.

1. $ python setup.py build


5. Run the following command to install the mysql-connector.

1. $ python setup.py install


This will take a bit of time to install mysql-connector for python. We can verify the installation once
the process gets over by importing mysql-connector on the python shell.

Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application to the
database.

There are the following steps to connect a python application to our database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection

To create a connection between the MySQL database and the python application, the connect()
method of mysql.connector module is used.

Pass the database details like HostName, username, and the database password in the method call.
The method returns the connection object.

The syntax to use the connect() is given below.

1. Connection-Object= mysql.connector.connect(host = <host-


name> , user = <username> , passwd = <password> )
Consider the following example.

Example
1. import mysql.connector
2. #Create the connection object

Compiled By : Mr. Vinod S Mahajan


3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
4. #printing the connection object
5. print(myconn)
Output:

<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>


Here, we must notice that we can specify the database name in the connect() method if we want to
connect to a specific database.

Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", dat
abase = "mydb")
4. #printing the connection object
5. print(myconn)
Output:

<mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>

Creating a cursor object

The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It facilitates
us to have multiple separate working environments through the same connection to the database. We
can create the cursor object by calling the 'cursor' function of the connection object. The cursor object
is an important aspect of executing queries to the databases.

The syntax to create the cursor object is given below.

1. <my_cur> = conn.cursor()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", dat
abase = "mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = myconn.cursor()

Compiled By : Mr. Vinod S Mahajan


10.
11. print(cur)

Creating the new database

The new database can be created by using the following SQL query.

1. > create database <database-name>


Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #creating a new database
11. cur.execute("create database PythonDB2")
12.
13. #getting the list of all the databases which will now include the new database PythonDB
14. dbs = cur.execute("show databases")
15.
16. except:
17. myconn.rollback()
18.
19. for x in cur:
20. print(x)
21.
22. myconn.close()
Output:

('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)

Compiled By : Mr. Vinod S Mahajan


('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)

Creating the table


In this section of the tutorial, we will create the new table Employee. We have to mention the
database name while establishing the connection object.

We can create the new table by using the CREATE TABLE statement of SQL. In our database
PythonDB, the table Employee will have the four columns, i.e., name, id, salary, and department_id
initially.

The following query is used to create the new table Employee.

1. > create table Employee (name varchar(20) not null, id int primary key, salary float not null
, Dept_Id int not null)
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Creating a table with name Employee having four columns i.e., name, id, salary, and dep
artment id
11. dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null pr
imary key, salary float not null, Dept_id int not null)")
12. except:
13. myconn.rollback()
14.
15. myconn.close()

Compiled By : Mr. Vinod S Mahajan


Now, we may check that the table Employee is present in the database.

Alter Table

Sometimes, we may forget to create some columns, or we may need to update the table schema. The
alter statement used to alter the table schema if required. Here, we will add the column branch_name
to the table Employee. The following SQL query is used for this purpose.

1. alter table Employee add branch_name varchar(20) not null


Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #adding a column branch name to the table Employee
11. cur.execute("alter table Employee add branch_name varchar(20) not null")
12. except:
13. myconn.rollback()
14.
15. myconn.close()

Insert Operation
Adding a record to the table

The INSERT INTO statement is used to add a record to the table. In python, we can mention the
format specifier (%s) in place of values.

We provide the actual values in the form of tuple in the execute() method of the cursor.

Consider the following example.

Example
1. import mysql.connector
2. #Create the connection object

Compiled By : Mr. Vinod S Mahajan


3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s
, %s)"
7.
8. #The row values are provided in the form of tuple
9. val = ("John", 110, 25000.00, 201, "Newyork")
10.
11. try:
12. #inserting the values into the table
13. cur.execute(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17.
18. except:
19. myconn.rollback()
20.
21. print(cur.rowcount,"record inserted!")
22. myconn.close()
Output:

1 record inserted!
Insert multiple rows

We can also insert multiple rows at once using the python script. The multiple rows are mentioned as
the list of various tuples.

Each element of the list is treated as one particular row, whereas each element of the tuple is treated
as one particular column value (attribute).

Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")

Compiled By : Mr. Vinod S Mahajan


5.
6. #creating the cursor object
7. cur = myconn.cursor()
8. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s
, %s)"
9. val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain")
,("Nick",104,90000.00,201,"Newyork")]
10.
11. try:
12. #inserting the values into the table
13. cur.executemany(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17. print(cur.rowcount,"records inserted!")
18.
19. except:
20. myconn.rollback()
21.
22. myconn.close()
Output:

3 records inserted!
Row ID

In SQL, a particular row is represented by an insertion id which is known as row id. We can get the
last inserted row id by using the attribute lastrowid of the cursor object.

Consider the following example.

Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6.
7. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s
, %s)"

Compiled By : Mr. Vinod S Mahajan


8.
9. val = ("Mike",105,28000,202,"Guyana")
10.
11. try:
12. #inserting the values into the table
13. cur.execute(sql,val)
14.
15. #commit the transaction
16. myconn.commit()
17.
18. #getting rowid
19. print(cur.rowcount,"record inserted! id:",cur.lastrowid)
20.
21. except:
22. myconn.rollback()
23.
24. myconn.close()
Output:

1 record inserted! Id: 0


Read Operation
The SELECT statement is used to read the values from the databases. We can restrict the output of a
select query by using various clause in SQL like where, limit, etc.

Python provides the fetchall() method returns the data stored inside the table in the form of rows. We
can iterate the result to get the individual rows.

In this section of the tutorial, we will extract the data from the database by using the python script.
We will also format the output to print it on the console.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.

Compiled By : Mr. Vinod S Mahajan


9. try:
10. #Reading the Employee data
11. cur.execute("select * from Employee")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15. #printing the result
16.
17. for x in result:
18. print(x);
19. except:
20. myconn.rollback()
21.
22. myconn.close()
Output:

1.9M
58
FOUR almighty pillars of OOP that can improve your PHP skills (from procedural to basics of
OOP)
('John', 101, 25000.0, 201, 'Newyork')
('John', 102, 25000.0, 201, 'Newyork')
('David', 103, 25000.0, 202, 'Port of spain')
('Nick', 104, 90000.0, 201, 'Newyork')
('Mike', 105, 28000.0, 202, 'Guyana')

Reading specific columns

We can read the specific columns by mentioning their names instead of using star (*).

In the following example, we will read the name, id, and salary from the Employee table and print it
on the console.

Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
4. #creating the cursor object

Compiled By : Mr. Vinod S Mahajan


5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee")
9.
10. #fetching the rows from the cursor object
11. result = cur.fetchall()
12. #printing the result
13. for x in result:
14. print(x);
15. except:
16. myconn.rollback()
17. myconn.close()
Output:

('John', 101, 25000.0)


('John', 102, 25000.0)
('David', 103, 25000.0)
('Nick', 104, 90000.0)
('Mike', 105, 28000.0)

The fetchone() method

The fetchone() method is used to fetch only one row from the table. The fetchone() method returns
the next row of the result-set.

Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:

Compiled By : Mr. Vinod S Mahajan


10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee")
12.
13. #fetching the first row from the cursor object
14. result = cur.fetchone()
15.
16. #printing the result
17. print(result)
18.
19. except:
20. myconn.rollback()
21.
22. myconn.close()
Output:

('John', 101, 25000.0)

Formatting the result

We can format the result by iterating over the result produced by the fetchall() or fetchone() method
of cursor object since the result exists as the tuple object which is not readable.

Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10.
11. #Reading the Employee data
12. cur.execute("select name, id, salary from Employee")
13.

Compiled By : Mr. Vinod S Mahajan


14. #fetching the rows from the cursor object
15. result = cur.fetchall()
16.
17. print("Name id Salary");
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20. except:
21. myconn.rollback()
22.
23. myconn.close()
Output:

Name id Salary
John 101 25000
John 102 25000
David 103 25000
Nick 104 90000
Mike 105 28000

Using where clause

We can restrict the result produced by the select statement by using the where clause. This will extract
only those columns which satisfy the where condition.

Consider the following example.

Example: printing the names that start with j


1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee where name like 'J%'")

Compiled By : Mr. Vinod S Mahajan


12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. print("Name id Salary");
17.
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20. except:
21. myconn.rollback()
22.
23. myconn.close()
Output:

Name id Salary
John 101 25000
John 102 25000
Example: printing the names with id = 101, 102, and 103
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee where id in (101,102,103)")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. print("Name id Salary");
17.
18. for row in result:

Compiled By : Mr. Vinod S Mahajan


19. print("%s %d %d"%(row[0],row[1],row[2]))
20. except:
21. myconn.rollback()
22.
23. myconn.close()
Output:

Name id Salary
John 101 25000
John 102 25000
David 103 2500

Ordering the result

The ORDER BY clause is used to order the result. Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee order by name")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. print("Name id Salary");
17.
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20. except:

Compiled By : Mr. Vinod S Mahajan


21. myconn.rollback()
22.
23. myconn.close()
Output:

Name id Salary
David 103 25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000

Order by DESC

This orders the result in the decreasing order of a particular column.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee order by name desc")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. #printing the result
17. print("Name id Salary");
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20.

Compiled By : Mr. Vinod S Mahajan


21. except:
22. myconn.rollback()
23.
24. myconn.close()
Output:

Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000

Update Operation
The UPDATE-SET statement is used to update any column inside the table. The following SQL query
is used to update a column.

1. > update Employee set name = 'alex' where id = 110


Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #updating the name of the employee whose id is 110
11. cur.execute("update Employee set name = 'alex' where id = 110")
12. myconn.commit()
13. except:
14.
15. myconn.rollback()
16.
17. myconn.close()

Compiled By : Mr. Vinod S Mahajan


Delete Operation

The DELETE FROM statement is used to delete a specific record from the table. Here, we must
impose a condition using WHERE clause otherwise all the records from the table will be removed.

The following SQL query is used to delete the employee detail whose id is 110 from the table.

x
1. > delete from Employee where id = 110
Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Deleting the employee details whose id is 110
11. cur.execute("delete from Employee where id = 110")
12. myconn.commit()
13. except:
14.
15. myconn.rollback()
16.
17. myconn.close()

******

Compiled By : Mr. Vinod S Mahajan

You might also like