0% found this document useful (0 votes)
32 views28 pages

Python Material Chapter-5-2024

Uploaded by

trushalkjk9227
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)
32 views28 pages

Python Material Chapter-5-2024

Uploaded by

trushalkjk9227
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/ 28

SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.

(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

CHAPTER – 5

CONNECTING WITH DATABASE

 Verifying the MySQL dB Interface Installation,


 Working with MySQL Database,
 Using MySQL from Python,
 Retrieving All Rows from a Table,
 Inserting Rows into a Table,
 Deleting Rows from a Table,
 Updating Rows in a Table,
 Creating Database Tables through Python

146
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

Q-1 What is Database and what is MySQL db?

 A database is basically a collection of structured data in such a way that it


can easily be retrieved, managed and accessed in various ways.
 One of the simplest forms of databases is a text database. Relational databases-
the most popular database system which includes the following:

 MySQL
 Oracle Database
 SQL server
 Sybase
 Informix
 IBM db2
 NO SQL

 Among all these databases, MySQL is one of the easiest databases to work with.
 Let me walk you through about this in detail.

What is MySQLdb?

 MySQLdb is an open-source freely available relational database


management system that uses Structured Query Language.
 Now one of the most important question here is “What is SQL?”
 SQL (Structured Query Language) is a standard language for relational
databases that allow users to do various operations on data like, Manipulating,
Creating, Dropping, etc.
 In a nutshell, SQL allows you to do anything with the data.

Q-2 Explain how does python connect to the MySQL database?

Detail :-
 It is very simple to connect Python with the database.
 Refer the below image which illustrates a Python connection with the
database where how a connection request is sent to MySQL connector
Python, gets accepted from the database and cursor is executed with result
data.

147
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

 Before connecting to the MySQL database, make sure you have


MySQL installer installed on your computer.
 It provides a comprehensive set of tools which helps in installing MySQL
with the following components

 MySQL server
 All available connectors
 MySQL Workbench
 MySQL Notifier
 Tools for Excel and Microsoft Visual Studio
 MySQL Sample Databases
 MySQL Documentation

1 Word Question – Answer

SR.NO QUESTION ANSWER

Before connecting to the MySQL database,


1 make sure you have installed on MySQL installer
your computer.

148
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

Q-3 How to verify installation of MySQL dB interface.

Detail :-

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.
 > python -m pip install mysql-connector

Or follow the following steps.

1. Click the link to download the source code :

https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7
b8660d09f91d8d5411298bcacbd309f96/mysql-connector-python-8.0.13.tar.gz

 Open the terminal (CMD for windows) and change the present
working directory to the source code directory.
 $ cd mysql-connector-python-8.0.13/

1. Run the file named setup.py with python (python3 in case you
have also installed python 2) with the parameter build.

 $ python setup.py build


Run the following command to install the mysql-connector

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

149
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

 Hence, we have successfully installed mysql-connector for python on


oursystem.
1 Word Question – Answer

SR.NO QUESTION ANSWER

To connect the python application


1 with the MySQL database, we must mysql.connector
import the module.
Command can be used
2 to install mysql-connector python setup.py

install

150
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

Q-4 Write note on working with MySQL Database.

Detail :-
Database Connection

 In this section ,we will discuss the steps to connect the python application
tothe database.
 There are the following steps to connect a python application to our database.

Import mysql.connector module

Create the connection object.

Create the cursor object 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.

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
3. myconn = mysql.connector.connect(host = "localhost", user =
"root",pass wd = "google")

151
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

4. #printing the connection object


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.

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
thesame connection to the database.
 We can create the cursor object by calling the 'cursor' function of
theconnection object.
 The cursor object is an important aspect of executing queries to
thedatabases.
The syntax to create the cursor object is given below

<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", database = "mydb")
4. #printing the connection object
5. print(myconn)6
6. creating the cursor
object
7. cur = myconn.cursor()
8. print(cur)

Output :-

152
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

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


MySQLCursor: (Nothing executed yet)

1 Word Question – Answer

SR.NO QUESTION ANSWER

To create a connection between the


1 MySQL database and the python connect()
application, the method can be
used.
The object is an important aspect
2 of executing queries to the databases. cursor

Q-5Write note on creating new MySQL Database.

Detail :-
 In this section , we will create the new database PythonDB.

Getting the list of existing databases

 We can get the list of all the databases by using the following MySQL query.
> show database
Example :-

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

4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd


= "google")

5. #creating the cursor object


6. cur = myconn.cursor()

153
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

7. try:
8. dbs = cur.execute("show databases")

9. except:
10. myconn.rollback()
11.for x in cur:
12. print(x)
13.myconn.close()

('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)

Creating the new database

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

> create database <database-

name> Example

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

6. try:
7. #creating a new database

154
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

8. cur.execute("create database PythonDB2")


9. #getting the list of all the databases which will now include the new
database PythonDB
10. dbs = cur.execute("show databases")

11. except:
12.
myconn.rollback
()13.for x in cur:
14. print(x)
15.myconn.close()

Output :-
('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schem
a',) ('javatpoint',)
('javatpoint1',)
('mydb',)

('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)
1 Word Question – Answer

SR.NO QUESTION ANSWER

The syntax for creating new database


1 is create database
<databasename>

155
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

Method can be used to


2 execute particular query. execute()

_ method can be used to close


3 the connection. close()

Q-6 Write note on creating Database Table through Python.

Detail :-
Creating the table

 In this section , 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.

> 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. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object

5. cur = myconn.cursor()

6. try:
7. #Creating a table with name Employee having four columns i.e.,
name, id, s alary, and department id
8. dbs = cur.execute("create table Employee(name varchar(20) not null, id int
(20) not null primary key, salary float not null, Dept_id int not null)")
9. except:

156
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

10. myconn.rollback()
11. Myconn.close()

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

alter table Employee add branch_name varchar(20) not null

Consider the following example.

157
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

1. import mysql.connector

2. #Create the connection object

3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd


= "google",database = "PythonDB")
4.
5. #creating the cursor object
6. cur = myconn.cursor()
7. try:
8. #adding a column branch name to the table Employee
9. cur.execute("alter table Employee add branch_name varchar(20) not null")
10. except:
11. myconn.rollback()
12. Myconn.close()

1 Word Question – Answer

SR.NO QUESTION ANSWER

Table can be created using


1 statement Create Table

158
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

module must be import to


2 connect with mysql. mysql.connector

__ ____ _method can be used to close


3 the connection. mysql.close()

Q-7 Write note on inserting rows into table.

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

Example :-

1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "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. #The row values are provided in the form of tuple8.
8. val = ("John", 110, 25000.00, 201, "Newyork")

9. try:
10. #inserting the values into the table
11. cur.execute(sql,val)
12. #commit the transaction
13. myconn.commi
t()14. except:
15. myconn.rollback()
16.print(cur.rowcount,"record
inserted!") 17.myconn.close()

159
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

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

Example :-
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
160
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

6. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (


%s, %s, %s, %s, %s)"

7. val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"P


ort of spain"),("Nick",104,90000.00,201,"Newyork")]
8. try:
9. #inserting the values into the table
10. cur.executemany(sql,val)
11. #commit the transaction
12. myconn.commit()
13. print(cur.rowcount,"records
inserted!")14.except:
15. myconn.rollback()
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 last rowid of
thecursor object.

161
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "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. val = ("Mike",105,28000,202,"Guyana")
8. try:
9. #inserting the values into the table

10. cur.execute(sql,val)
11. #commit the transaction
12. myconn.commit()
13. #getting rowid
14. print(cur.rowcount,"recordinserted! id:",cur.lastrowid)
15. except:
16.myconn.rollback
()17.myconn.close()

Output :-

1 record inserted! Id: 0


1 Word Question – Answer

SR.NO QUESTION ANSWER

The statement is used to


1 add a record to the table. insert into
In SQL, a particular row is represented
2 by an insertion id which is known row id
as
We can also insert multiple rows at once
3 using . python script

162
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

Q-8Write note on Retrieving all the rows from a table.

Detail :-
Read Operation

 You can use either fetchone() method to fetch single record or fetchall()
method to fetech multiple values from a database table.

 fetchone() − It fetches the next row of a query result set. A result set is
anobject that is returned when a cursor object is used to query a table.
 fetchall() − It fetches all the rows in a result set. If some rows have
already been extracted from the result set, then it retrieves the remaining
rows fromthe result set.
 rowcount − This is a read-only attribute and returns the number of rows
that were affected by an execute() method

 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
tablein 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. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",
passwd= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select * from Employee")

163
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

9. #fetching the rows from the cursor object


10. result = cur.fetchall()
11. #printing the result
12. for x in result:
13. print(x);
14.except:
15.myconn.rollback()
16.myconn.close()
/*Output:

('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",
4. passwd= "google",database = "PythonDB")
5. #creating the cursor object
6. cur = myconn.cursor()

7. try:
8. #Reading the Employee data
9. cur.execute("select name, id, salary from Employee")

164
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

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.rollbac
k() 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.

Example :-

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

165
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

12. print(result)

13.except:
14. myconn.rollback()
15. 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.

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

5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee")
9. #fetching the rows from the cursor object
10. result = cur.fetchall()
11. print("Name id Salary");
12. for row in result:
13. print("%s %d
%d"%(row[0],row[1],row[2])) 14.except:
15. myconn.rollback()
16. myconn.close()
Output :-
Name Id Salary
John 101 25000
John 102 25000
David103 25000
166
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

Nick 104 90000


Mike 105 28000

Using where clause

 We can restrict the result produced by the select statement by using


thewhere clause.
 This will extract only those columns which satisfy the where condition.

Example: printing the names that start with j

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

6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee where name like 'J%'")

9. #fetching the rows from the cursor object


10. result = cur.fetchall()
11. print("Name id Salary");
12. for row in result:
13. print("%s %d
%d"%(row[0],row[1],row[2])) 14.except:
15.myconn.rollback
()16.myconn.close()

Name id
Salary John
101
25000
John 102 25000

167
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

Example: printing the names with id = 101, 102, and 103

Example :-

1. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd


= "google",database = "PythonDB")
2. #creating the cursor object
3. cur = myconn.cursor()
4. try:

5. #Reading the Employee data


6. cur.execute("select name, id, salary from Employee where id in
(101,102,1 03)")
7. #fetching the rows from the cursor object
8. result = cur.fetchall()
9. print("Name id Salary");
10. for row in result:
13. print("%s %d
%d"%(row[0],row[1],row[2]))
14.except:
15. myconn.rollback()

16.myconn.close()

Ordering the result

 The ORDER BY clause is used to order the result.

Example

1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
168
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

8. cur.execute("select name, id, salary from Employee order by name")


9. #fetching the rows from the cursor object
10. result = cur.fetchall()
11. print("Name id Salary");
12. for row in result:
13. print("%s %d %d"%(row[0],row[1],row[2]))
14.except:
15.myconn.rollback
()16.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. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select name, id, salary from Employee order by name desc")
9. #fetching the rows from the cursor object
10. result = cur.fetchall()
169
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

11. #printing the result


12. print("Name id Salary");
13. for row in result:
14.print("%s %d %d"%(row[0],row[1],row[2])) \
15.
15.except:
16. myconn.rollback()
17.myconn.close()

Output:

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

1 Word Question – Answer

SR.NO QUESTION ANSWER

method can be used to


1 fetch single record fetchone()
method fetches all the
2 rows in a result set fetchall()

method is used to returns the


3 number of rows that were affected. rowcount()

Q-9Write note on Updating Rows in a table.

Detail :-
Update Operation

170
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

 The UPDATE-SET statement is used to update any column inside the table.
 The following SQL query is used to update a column.
 UPDATE Operation on any database means to update one or more
records, which are already available in the database.

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


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

171
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

1 Word Question – Answer

SR.NO QUESTION ANSWER

statement is used to update any


1 column inside the table. UPDATE-SET

__ ____method can be used to save the


2 updation on record. commit()

Q-10Write note on Deleting Rows from a table.

Detail :-

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.

> delete from students where rollno = 4

1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd
= "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Deleting the student details whose rollno is 4

172
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)

2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001

8. cur.execute("delete from students where rollno = 4")


9. myconn.commit()

10.except:
11.myconn.rollback
()12.myconn.close()

1 Word Question – Answer

SR.NO QUESTION ANSWER

The statement is used


1 to delete a specific record from the DELETE FROM
table.
clause must be used to
2 remove or delete particular record from WHERE
the table.

173

You might also like