Python Material Chapter-5-2024
Python Material Chapter-5-2024
2 – Vaishalinagar 3 – Vaishalinagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot – 360001
CHAPTER – 5
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
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?
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
MySQL server
All available connectors
MySQL Workbench
MySQL Notifier
Tools for Excel and Microsoft Visual Studio
MySQL Sample Databases
MySQL Documentation
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
Detail :-
Install mysql.connector
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.
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
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
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.
Connection-Object= mysql.connector.connect(host =
<host- name> , user = <username> , passwd =
<password> )
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
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.
<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
Detail :-
In this section , we will create the new database PythonDB.
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
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',)
The new database can be created by using the following SQL query.
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
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
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
Detail :-
Creating the table
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
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
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
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!
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
Output :-
3 records inserted!
Row ID
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 :-
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
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
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 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)
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
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%'")
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 :-
16.myconn.close()
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
Output:
Name id
Salary
David 103
25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000
Order by DESC
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
Output:
Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
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.
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
Detail :-
Delete Operation
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
10.except:
11.myconn.rollback
()12.myconn.close()
173