0% found this document useful (0 votes)
115 views61 pages

SQL Python Connectivity

This document discusses connecting Python to MySQL for database operations. It explains that MySQL is used as the backend database and Python as the frontend interface. It provides steps to establish this connectivity which includes installing required packages like MySQL connector, creating a connection object, acquiring a cursor, and executing SQL queries. Examples are given for connecting Python to MySQL, creating databases and tables, and inserting records. The key points covered are the use of mysql.connector package, connect() method to create a connection, cursor() method to get a cursor object, and execute() method to run SQL statements.

Uploaded by

Movie ghar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
115 views61 pages

SQL Python Connectivity

This document discusses connecting Python to MySQL for database operations. It explains that MySQL is used as the backend database and Python as the frontend interface. It provides steps to establish this connectivity which includes installing required packages like MySQL connector, creating a connection object, acquiring a cursor, and executing SQL queries. Examples are given for connecting Python to MySQL, creating databases and tables, and inserting records. The key points covered are the use of mysql.connector package, connect() method to create a connection, cursor() method to get a cursor object, and execute() method to run SQL statements.

Uploaded by

Movie ghar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 61

Python – MySQL Connectivity

Front-end and Back-end


In Real life application, the data inputted by the user
are required to be saved permanently, so that stored
data can be used for future manipulation
 An application usually stores the data in the form of
a database and
 make the database accessible to the user through a
user friendly interface.
The interface through which user access the database
is referred as Front End.
The database which stores the data is known as Back
End
MySQL as Back-end Interface
MySQL is a relational database management system
(RDBMS) based on the SQL (Structured Query Language)
queries.
 MySQL can be downloaded, installed, and executed on
most of the available operating systems.
 MySQL follows the working of a client/server architecture.
The database created by MySQL woks as a server and
many application programs as clients can communicate
with the database.
 MySQL is considered one of the very fast database
language, backed by a large number of the benchmark
test.
 MySQL supports a large number of embedded
applications, which makes MySQL very flexible.
Python as Front-end Interface
Python Programming Language is a flexible, portable, easy-to-
learn programming language.
The several reasons why Python is used to develop Database
applications are :
 Programming more efficient and faster compared to other
languages.
 Portability feature of python is efficient and it supports
platform independent program development.
 Python supports relational database systems.
 Python itself takes care of open and close of connections.
It also supports SQL cursors for accessing data from
database.
 Porting of data from one DBMS to other is easily possible as
it support large range of APIs (Application Programming
Interface) for various databases.
Connecting Python To MySQL
To establish Connectivity between Python and MySQL,
Python Database Interface and APIs (Application
Programming Interface )are required.
The DB-API provides a simple interface for working with
databases using Python programming structures. This API
includes :
 Importing the API module.
 Acquiring a connection with the database.
 Issuing SQL statements
 Closing the connection
To connect python program with MySQL it is required to
build a bridge to connect Python and MySQL and this is
achieved by importing Python library MySQL connector
(mysql.connector).
Connecting Python To MySQL

To establish connectivity between Python and MySQL, the


MySQL connector need to be installed.
For a successful installation, the points to be kept in mind
are :
 Download Python 3.8 and install it.
 Download MySQL API and install it.
 Install MySQL and Python Connector
 Connect MySQL server using Python

Note : MySQL connector requires Python to be in the


system’s PATH. Installation fails if it doesn’t find Python.
Connecting Python To MySQL

Once the connector is installed, connectivity between


Python program and MySQL can be achieved using
the following steps.
 Open python
 Import the package required mysql.connector
 Open the connection to database
 Create a cursor instance
 Execute the query and store it in resultset
 Extract data from resultset
 Clean up the environment
Importing mysql.connector Package
To import MySQL connector package, include the
following import statement in the Python program/
prompt
 import mysql.connector
If the above code runs without any errors, then
mysql.connector is successfully installed and it is ready to
use.
The above import statement can also be given as :
 import mysql.connector as ms
Here “ms” is an alias, so every time “ms” can be used in
place of “mysql.connector”
connect() To Connecting Python To MySQL
To create a connection between the MySQL database and the python application, the
connect() method of mysql.connector module is used which creates a connection and
returns a MySQL connection object.
Syntax to use the connect() :
Connection-Object
= mysql.connector.connect(host = <hostname> , user = <username> , passwd = <passwor
d> )
 Host Name – is the server name or Ip address on which MySQL is running. When the
database is in local computer, host = “localhost” is used,
 Username – The username refers to the user name in MySQL Server. The default
username for the MySQL database is root
 Password – Password is given by the user at the time of installing the MySQL database.
When Password is not there two blank as password (consecutive "") are given.
The user has to ensure that the user and password specified should match to the user
and password given for local MySQL installation.
 The connection object is an identifier which can be used for executing queries and
other tasks on connected database
Note : database=<database name> can also be given after passwd if the application is
manipulating an existing database .
Example of the connect() method
mydb = mysql.connector.connect (host = "localhost", user = "root", passwd =
"student")
 Host as localhost
 User as root
 Password as student
 Mydb is the connection object
If the above statement reports no error then the connection is successful. The
is_connected() method can be used to check successful connection which returns
True when connection is successful.
Example :
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root",passwd="student")
if mydb.is_connected():
print("success")
When given with alias, the alias can be used in place of “mysql.connector”
Example :
import mysql.connector as sqlcon
Mydb= sqlcon.connect(host="localhost", user = "root",passwd = "student")
Creating cursor object using cursor() method
After creating the connection object, the next step for interacting with
MySQL from Python is to create cursor object.
The cursor is a useful control structure of database connectivity which allows
row-by-row processing of the result sets. In Python it is achieved through
cursor object.
Cursor object is created by cursor() method.
The cursor object is used to execute MySQL commands and to access
retrieved records from the database.
The cursor() method is invoked through connection object and it returns the
cursor object .
Syntax : Cursor_name = connectionObject.cursor()
Example :
import mysql.connector
mydb = mysql.connector.connect(host = "localhost", user = "root",passwd =
"student")
mycur = mydb.cursor()
In the above example the cursor object returned by the cursor() is assigned
to mycur cursor object.
Execution of SQL query using execute()
When any statement for execution of query is given in Python
 the query is sent to the server where it gets executed and
 the set of record retrieved as the result of command execution (Result set) is
transferred over the connection to the application program in one go.
Result set refers to a logical set of records that are fetched from the database by
executing a SQL query and made available to the application program.
The execute() method is used execute SQL query from Python where the SQL
command is given as a string.
Syntax : cursor_object.execute(“SQL query string”)
Example :
import mysql.connector
mydb = mysql.connector.connect (host="localhost", user="root", passwd = "student")
mycur = mydb.cursor() #cursor object created
mycur.execute("CREATE DATABASE EMPDB")#execution of create database
mycur.execute("USE EMPDB") #Execution of command to open the database
As MySQL is not case sensitive, the SQL command to be executed can be given in
any case as a string literal enclosing it in double quotes.
Creation of Database and Opening Database Through Python
To create the database the MySQL command Create Database is used :
Syntax : CREATE <Database name>
Before creating the database, it is advisable to check whether the database
already exists or not. If the database creation command is given for an existing
database, it will result an exception. To handle the exception, the exception handler
can be given in try and except block.
To open the database the Use command is used
Syntax : USE <Database Name>
Example :
try:
mycur.execute("CREATE DATABASE EMPDB") #Database creation command
print("Database Created")
except:
print("***Database exists..Creation of Database not required***")
mycur.execute("USE EMPDB")
In the above code, if the database is already existing, then control goes to except
block and the message "***Database exists..Creation of Database not required***“
will be displayed.
The next execute statement will open the database EMPDB and make it active.
Creation of Table Through Python
To create the a table in MySQL the Create Table command used is :
Syntax :
Create Table <table-name>(<column name1> <data type> <size> , <column
name2> <data type> [(<size>]...);
Before creating the table, it is advisable to include the exception handler to
check if the table exists or not. If the table creation command is given for an
existing table, it will result an exception.
Example :
try:
mycur.execute("CREATE TABLE EMP(EMPNO INT(3) PRIMARY KEY, NAME
VARCHAR(25), SALARY DECIMAL(12,2),DEPT VARCHAR(5), DOB DATE)")
except:
print("***Table exists..Table Creation Not Required***")
In the above code, if the table creation command is given for the already
created table EMP , then control goes to except block and the message
"***Table exists..Table Creation not required***“ will be displayed.
Otherwise the table EMP with the above specifications will be created under
the currently active database.
Inserting Records Into Table Through Python
To insert record into table in MySQL the insert command used is :
Syntax : INSERT INTO <table name> VALUES(<value1>, < value2, ....);
After the table is created the insert statement can be used to add record to the
table.
After performing any DML operations such as INSERT, DELETE and UpDATE , it is
mandatory to commit the DML by executing commit method from Database
Connection Object, Otherwise, the changes will not get reflected in the table
Syntax : <Connction_Object>.commit()
Example : mydb.commit()
Example : Inserting record into emp table
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd = "student")
mycur = mydb.cursor()
Mycur.execute("INSERT INTO EMP VALUES(1, ‘Akash’, 20000, ‘Accts’, “’002-01-12’)")
mydb.commit()
To insert multiple records multiple execute statements with different records can be
given
Inserting Records Into Table Through Python
To insert record into the table by accepting the data from the user in Python interface,
the steps are
 Accept the details from user into different objects for each field
 Form a sting object by concatenating these objects with insert into statement
 Use the string object as the argument of execute method
Example : Inserting User given record into emp table
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd = "student")
mycur = mydb.cursor()
#Data inputted from user
eno = input("Enter Employee No -")
name = input("Enter Employee Name -")
salary = input("Enter salary -")
dept = input("Enter Department -")
dob = input("date of Birth -")
# insert statement formed as string object st
st = "INSERT INTO EMP VALUES("+eno+",’ “+name+“ ‘, "+salary+", ‘ " +dept+ “ ‘, ‘”+dob+ “ ‘)"
Mycur.execute(st)
mydb.commit()
Inserting user given Records Into Table Till User wants
Example : Inserting User given record into emp table till User wants
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd = "student")
mycur = mydb.cursor()
# loop to accept values and execute inser satement
while True:
eno = input("Enter Employee No -")
name = input("Enter Employee Name -")
salary = input("Enter salary -")
dept = input("Enter Department -")
dob = input("date of Birth -")
st = "INSERT INTO EMP VALUES("+eno+", ' "+name+" ',"+salary+", ' "+dept+" ',' "+dob+" ')"
mycur.execute(st) #insert statement executed
ans = input("want to Enter another(y/Y")
if ans in ("N","n"):
break
mydb.commit()
Query Operation in MySQL Database
Query Operation on any database means to fetch some useful
information from the database. Queries enable users to search and
retrieve records that meet certain criteria and to manipulate it
Once the database connection is established, the SQL statement can
be given to make a query. A result set is an object that is returned
when a cursor object is used to query a table.
The query which may fetch one record or multiple records from the
table, hence Result set can have one or many records.
 fetchone() − The fetchone() method is used to fetch a single record
from the Result set as a tuple. When given, First time it will return first
record, next time it will return second record and so on. If no more
record it will return None.
Syntax : object = Cursor_Object.fetchone()
 fetchall() − It fetches all the rows in a result set in the form of List of
tuple. If some rows have already been extracted from the result set,
then it retrieves the remaining rows from the result set.
Syntax : object = Cursor_Object.fetchall()
Query Operation in MySQL Database
 fetchmany(<n>) − This method accepts no. of
records to fetch (n) and returns a tuple where each
record is represented as one tuple. When called
repeatedly this method fetches the next set of rows
of a query result and returns a list of tuples. If no more
rows are available, it returns an empty list.
Syntax : object = Cursor_Object.fetchmany(n)

 rowcount − This is a read-only attribute of a cursor


Object which returns the number of rows that were
affected by an execute() method. If none of the
records are fetched, then it will have value 0.
<object> = Cursor_Object.rowcount
Closing Connection And Cursor
Closing Connection Object
 Although, Connections are automatically closed when they go
out of scope), it is a good practice to close the connection
object and cursor object.
 Once the database operation in Python interface is done using
the close() method with the connection object, it can be
closed.
 Syntax : <Connection_object>.close()
 Example : mydb.close()

Closing Cursor Object


 The close() method used with cursor object closes the cursor,
resets all results, and ensures that the cursor object has no
reference to the original connection object.
 Syntax : <Cursor _object>.close()
 Example : mycur.close()
SELECT Statement To do Query Operation
Select statement of MySQL is used to retrieve data from tables.
 Selecting all records from table
Syntax : SELECT * FROM <Table Name>;
will retrieve all data from the specified table
 Execute() to execute SELECT statement to retrieve all rows
mycur.execute("SELECT * FROM EMP") #Execute the SELECT statement
recs = mycur.fetchall() #recs will be have all the records of the file EMP
 The recs is holding all the records and as it is a list object it can be
manipulated using for loop and membership operator (in)
Method 1 to Display records
 for r in recs:
print(r)
Output :
(1, 'Akash', Decimal('20000.00'), 'Accts', datetime.date(2002, 1, 12))
(2, 'jimmy', Decimal('40000.00'), 'Sys', datetime.date(1995, 1, 1))
(3, 'Rajesh', Decimal('50000.00'), 'Accts', datetime.date(1985, 10, 10))
The above method displays the record one by one with the datatype of field
which are not of char and Int data type.
SELECT Statement To do Query Operation
Method -2 To Display records
 for eno,name,sal,dept,dob in recs:
print(eno,"\t",name,"\t",sal,"\t",dept,"\t",dob)
Output :
1 Akash 20000.00 Accts 2002-01-12
2 jimmy 40000.00 Sys 1995-01-01
3 Rajesh 50000.00 Accts 1985-10-10
The above method displays the record one by one and shows the data
type of the non-char data type.
Method -3 To Display records
 for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep="\t")
Output :
1 Akash 20000.00 Accts 2002-01-12
2 jimmy 40000.00 Sys 1995-01-01
3 Rajesh 50000.00 Accts 1985-10-10
SELECT Statement To do Query Operation
Example : Program to display all records stored in the table Emp with total no. of
records present in it
Program :
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd="student")
mycur=mydb.cursor()
mycur.execute("SELECT * FROM EMP")
recs=mycur.fetchall()
ctr = mycur.rowcount #counting total records present in the record set
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep="\t")
print("\nTotal records in the table -",ctr)

Output : 1 Akash 20000.00 Accts 2002-01-12


2 jimmy 40000.00 Sys 1995-01-01
3 Rajesh 50000.00 Accts 1985-10-10
Total records in the table - 3
SELECT Statement To Search based On a Condition
To perform conditional query operation on a table and retrieve rows matching with a given
criteria, WHERE clause with SELECT statement is used. WHERE clause with SELECT statement
output only those rows, which satisfy the specified condition.
Example : Program to display the details of an employee matching with a user given emp no.
Program :
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd="student")
mycur=mydb.cursor()
seno=input("enter employee no to search -")
st ="SELECT * FROM EMP WHERE Empno="+seno+"“ #string to represent SELECT command
mycur.execute(st) #Execute the statement
rec = mycur.fetchone() #Retrive the record
ctr = mycur.rowcount
if ctr == 0:
print("No such record") #When no match found ctr will have 0
else:
print("Record Found...Details -")
print("Employee No - ",rec[0])
print("Name - ",rec[1])
print("Salary - ",rec[2])
print("Department -",rec[3])
print("Date Of Birth - ",rec[4])
SELECT Statement To Search based On a Condition
Example : Program to display the details of an employee matching with a user
given employee name.
Program :
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd="student")
mycur=mydb.cursor()
senm=input("enter employee name to search -")
st = "SELECT * FROM EMP WHERE name=' "+senm+" ' "
mycur.execute(st)
recs=mycur.fetchall()
ctr=mycur.rowcount
for r in recs:
print("Employee No - ",r[0])
print("Salary - ",r[2])
print("Department -",r[3])
print("Date Of Birth - ",r[4])
if ctr==0:
print("No such Record")
SELECT Statement To Search based On a Condition
Example : Program to display the details of an employee whose date of birth is
after than a user given employee DATE.
Program :
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd="student")
mycur=mydb.cursor()
SDOB=input("enter date to search -")
st = "SELECT * FROM EMP WHERE DOB>’ “+SDOB+" ' "
mycur.execute(st)
recs=mycur.fetchall()
ctr=mycur.rowcount
for r in recs:
print("Employee No - ",r[0])
print(“name”,r[1])
print("Salary - ",r[2])
print("Department -",r[3])
print("Date Of Birth - ",r[4])
if ctr==0:
print("No such Record")
print(ctr)
SELECT Statement To Search & Count based On a Condition
Example : Program to count and display the details of an employee matching
with a user given department.
Program :
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd="student")
mycur=mydb.cursor()
sdpt=input("enter Department name to search and Count -")
st = "SELECT * FROM EMP WHERE Dept = ' "+sdpt+" ' "
mycur.execute(st)
recs=mycur.fetchall()
ctr=mycur.rowcount
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep="\t")
if ctr == 0:
print("No records")
else:
print("No of employees in Department",sdpt," are - ",ctr)
SELECT Statement To Search & Count based On a Condition
Example : Program to count the number of employee earning >= a user given
salary.
Program :
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd="student")
mycur=mydb.cursor()
ssal=input("enter salary to Count -")
st = "SELECT * FROM EMP WHERE salary >= "+ssal+""
mycur.execute(st)
rec = mycur.fetchall()
ctr = mycur.rowcount
if ctr == 0:
print("No records")
else:
print("No of employees earning >=",ssal," - ",ctr)
SELECT To display records arranged in ascending order of Name

Example : Program to display the records arranged in ascending order of name


Program :
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd="student")
mycur=mydb.cursor()
mycur.execute("SELECT * FROM EMP ORDER BY Name")
recs=mycur.fetchall()
ctr=mycur.rowcount
print("Total records -",ctr)
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep="\t")
Deleting Record in MySQL Table Using Python
Deleting operation refers to removal of one or more record which are
already available in the table.
DELETE command of MySQL removes records stored in a table. The
WHERE clause used with DELETE will remove record(s) matching a
given condition. When DELETE command is used without the WHERE
clause, It will remove all the records present in the table.
Syntax DELETE FROM <tablename> WHERE <condition>;
In Python, to delete record(s) from MySQL table the steps are :
 The connection object and cursor object is created
 The DELETE command is framed and assigned to a string object
 Execution of the DELETE statement is done by passing the string
object storing the DELETE statement as a parameter to
the execute() method.
 Then commit() is used to make the changes reflect in the table
Deleting Records in MySQL Table Using Python
Example : Program to delete the record of an employee by accepting the Emp no from user.
import mysql.connector
mydb=mysql.connector.connect (host = "localhost", user = "root", passwd = "student")
mycur=mydb.cursor()
seno=input("enter employee no to delete -")
st="SELECT * FROM EMP WHERE Empno="+seno+" "
mycur.execute(st)
rec=mycur.fetchone()
ctr=mycur.rowcount
delst = "DELETE FROM EMP WHERE Empno="+seno+" "
if ctr == 0:
print("No such record")
else:
print("Record to be Deleted Found...Details -")
print("Employee No - ",rec[0], "\n", Name - ",rec[1], "\n“,"Salary - ",rec[2])
print("Department -",rec[3])
print("Date Of Birth - ",rec[4])
confirm=input("Do you want to delete this record (y/n - )")
if confirm in("y",“Y"):
mycur.execute(delst) #Delete statement executed
print("record Deleted")
mydb.commit() #Deletion committed
Deleting Records in MySQL Table Using Python
Example : Program to delete the record of an employee by accepting the Emp Name
from user.
import mysql.connector
mydb=mysql.connector.connect (host = "localhost", user = "root", passwd = "student")
mycur=mydb.cursor()
senm=input("enter employee name to delete -")
st = "SELECT * FROM EMP WHERE name = ' "+senm+" ' "
mycur.execute(st)
recs=mycur.fetchall()
ctr = mycur.rowcount
delst="DELETE FROM EMP WHERE name = ' "+senm+" ' "
for r in recs:
print("Employee No - ",r[0])
print("Salary - ",r[2])
print("Department -",r[3])
print("Date Of Birth - ",r[4])
confirm=input("Do you want to delete the record(s) (y/n - )")
if confirm in("y","y"):
mycur.execute(delst)
print("record Deleted")
mydb.commit()
print(ctr, "No. of records deleted“)
Editing Records in MySQL Table Using Python
Editing operation refers to change the content of one or more record
which are already available in the table.
Update command of MySQL changes or modifies data values stored in
a table. The WHERE clause used with UPDATE will allow updating
record(s) matching a given condition. When UPDATE command is used
without the WHERE clause, the updation will be applicable for all the
records.
Syntax : Update <tablename> SET <columnname> = < arithmetic
expression> WHERE <condition>;
In Python, to edit the details of MySQL table the steps are :
 The connection object and cursor object is created
 The UPDATE command is framed and assigned to a string object
 Execution of the UPDATE statement is done by passing the string
object storing the UPDATE statement as a parameter to
the execute() method.
 Then commit() is used to make the changes reflect in the table
Editing Records in MySQL Table Using Python
Example : Program to edit the record of an employee by accepting the Emp no from user.
import mysql.connector
mydb=mysql.connector.connect (host = "localhost", user = "root", passwd = "student")
mycur=mydb.cursor()
seno=input("enter employee no to Edit -")
st="SELECT * FROM EMP WHERE Empno="+seno+" "
mycur.execute(st)
rec=mycur.fetchone()
ctr=mycur.rowcount
if ctr == 0:
print("No such record")
else:
print("\nRecord To Be Edited Found...Details -")
print("Employee No - ",rec[0], "\n", Name - ",rec[1], "\n“,"Salary - ",rec[2])
print("Department -",rec[3])
print("Date Of Birth - ",rec[4])
confirm=input("\nDo you want to Edit the record(s) (y/n - )")
if confirm in("y",“Y"):
newsal=input("enter changed salary")
updst="UPDATE EMP set salary="+newsal+" WHERE Empno="+seno+" "
mycur.execute(updst) #UPDATE STATEMENT EXECUTED
mydb.commit() #UPDATION COMMITTED
Closing Connection And Cursor
Closing Connection Object
 Although, Connections are automatically closed when they go
out of scope), it is a good practice to close the connection
object and cursor object.
 Once the database operation in Python interface is done using
the close() method with the connection object, it can be
closed.
 Syntax : <Connection_object>.close()
 Example : mydb.close()

Closing Connection Object


 The close() method used with cursor object closes the cursor,
resets all results, and ensures that the cursor object has no
reference to the original connection object.
 Syntax : <Cursor _object>.close()
 Example : mycur.close()
Employee Details Manipulation Using MySQL-Python
The menu driven application is using MySQL Database Connectivity using Python. In a
menu driven interface it is providing the following features
1. INSERT NEW RECORDS
2. DISPLAY ALL RECORDS
3. SEARCH & DISPLAY
4. COUNT & DISPLAY
5. DELETE RECORD
6. EDIT RECORD
7. ARRANGE RECORDS IN ASCENDING & DESCENDING ORDER
Program :
import mysql.connector
mydb=mysql.connector.connect (host = "localhost", user = "root", passwd = "student")
if mydb.is_connected():
print("success")
mycur=mydb.cursor()
try:
mycur.execute("CREATE DATABASE EMPDB")
print("Database Created")
except:
print("***Database exists..Creation of Database not required***")
Employee Details Manipulation Using MySQL-Python
mycur.execute("USE EMPDB") #Database opened
try:
mycur.execute("CREATE TABLE EMP(EMPNO INT(3) PRIMARY KEY, NAME VARCHAR(25),
SALARY DECIMAL(12,2),DEPT VARCHAR(5), DOB DATE)")
print("Table Created..add records now")
except:
print("***Table exists..Table Creation Not Required***")
def insert(): #UDF to insert records
while True:
eno = input("Enter Employee No -")
name = input("Enter Employee Name -")
salary = input("Enter salary -")
dept = input("Enter Department -")
dob=input("date of Birth -")
st = "INSERT INTO EMP VALUES("+eno+",' "+name+" ',"+salary+",' "+dept+" ',' "+dob+" ')"
mycur.execute(st)
ans = input("want to Enter another(y/Y")
if ans in ("N","n"):
break
mydb.commit()
Employee Details Manipulation Using MySQL-Python
def showrecs(): #UDF to display all records
mycur.execute("SELECT * FROM EMP")
recs = mycur.fetchall()
ctr = mycur.rowcount
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep = "\t")
print("\nTotal records in the table -",ctr)
def searcheno(): #UDF to search on emp no
seno=input("enter employee no to search -")
st = "SELECT * FROM EMP WHERE Empno = "+seno+" " #String with SELECT statement
mycur.execute(st)
rec = mycur.fetchone()
ctr = mycur.rowcount
if ctr==0:
print("No such record")
else:
print("Record Found...Details -")
print("Employee No - ",rec[0])
print("Name - ",rec[1])
print("Salary - ",rec[2])
print("Department -",rec[3])
print("Date Of Birth - ",rec[4])
Employee Details Manipulation Using MySQL-Python
def searchname(): #UDF to search on emp name
senm = input("enter employee name to search -")
st = "SELECT * FROM EMP WHERE name=' "+senm+" ' "
mycur.execute(st)
recs = mycur.fetchall()
ctr = mycur.rowcount
for r in recs:
print("Employee No - ",r[0])
print("Salary - ",r[2])
print("Department -",r[3])
print("Date Of Birth - ",r[4])
if ctr == 0:
print("No such Record")
def countsal(): #UDF to count records >=given salary
ssal = input("enter salary to Count -")
st = "SELECT * FROM EMP WHERE salary >= "+ssal+" "
mycur.execute(st)
rec=mycur.fetchall()
ctr=mycur.rowcount
if ctr == 0:
print("No records")
else:
print("No of employees earning >=", ssal ,” - ",ctr)
Employee Details Manipulation Using MySQL-Python
def countdept():
sdpt = input("enter Department name to search and Count -")
st = "SELECT * FROM EMP WHERE Dept=' "+sdpt+" ' "
mycur.execute(st)
recs = mycur.fetchall()
ctr = mycur.rowcount
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep="\t")
if ctr == 0:
print("No records")
else:
print("No of employees in Department",sdpt," are - ",ctr)

def show_name_asc():
mycur.execute("SELECT * FROM EMP ORDER BY Name")
recs = mycur.fetchall()
ctr = mycur.rowcount
print("Total records -",ctr)
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep="\t")
Employee Details Manipulation Using MySQL-Python
def show_name_desc(): #UDF to display records in descending order of name
mycur.execute("SELECT * FROM EMP ORDER BY Name DESC")
recs = mycur.fetchall()
ctr = mycur.rowcount
print("Total records - ", ctr)
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep = "\t")

def show_salary_asc(): #UDF to display records in ascending order of salary


mycur.execute("SELECT * FROM EMP ORDER BY Salary")
recs = mycur.fetchall()
ctr = mycur.rowcount
print("Total records - ",ctr)
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep = "\t")

def show_salary_desc(): #UDF to display records in descending order of salary


mycur.execute("SELECT * FROM EMP ORDER BY Salary Desc")
recs = mycur.fetchall()
ctr = mycur.rowcount
print("Total records -",ctr)
for r in recs:
print(r[0],r[1],r[2],r[3],r[4],sep = "\t")
Employee Details Manipulation Using MySQL-Python
def editsal_eno(): #UDF to edit salary seaching on user given emp no
seno=input("enter employee no to Edit -")
st = "SELECT * FROM EMP WHERE Empno = "+seno+" "
mycur.execute(st)
rec = mycur.fetchone()
ctr = mycur.rowcount
if ctr == 0:
print("No such record")
else:
print("\nReord Found...Details -")
print("Employee No - ",rec[0])
print("Name - ",rec[1])
print("Salary - ",rec[2])
print("Department -",rec[3])
print("Date Of Birth - ",rec[4])
confirm=input("\nDo you want to Edit the record(s) (y/n - )")
if confirm in("y","Y"):
newsal=input("enter changed salary")
updst="UPDATE EMP set salary = "+newsal+" WHERE Empno = "+seno+""
mycur.execute(updst)
print("\nrecord Updated")
mydb.commit()
else:
return
Employee Details Manipulation Using MySQL-Python
def deleno(): #UDF to delete record on the basis on Emp no
seno=input("enter employee no to delete -")
st = "SELECT * FROM EMP WHERE Empno = "+seno+" "
mycur.execute(st)
rec =mycur.fetchone()
ctr = mycur.rowcount
if ctr == 0:
print("No such record")
else:
print("Record Found...Details -")
print("Employee No - ",rec[0])
print("Name - ",rec[1])
print("Salary - ",rec[2])
print("Department -",rec[3])
print("Date Of Birth - ",rec[4])
confirm = input("Do you want to delete this record (y/n - )")
if confirm in("y",“Y"):
delst = "DELETE FROM EMP WHERE Empno = "+seno+" “
mycur.execute(delst)
print("record Deleted")
mydb.commit()
else:
return
Employee Details Manipulation Using MySQL-Python
def delname(): #UDF to delete record on the basis on Emp no
senm=input("enter employee name to delete -")
st="SELECT * FROM EMP WHERE name='"+senm+"'"
mycur.execute(st)
recs = mycur.fetchall()
ctr = mycur.rowcount
if ctr == 0:
print(“No record found“)
else:
for r in recs:
print("Employee No - ",r[0])
print("Salary - ",r[2])
print("Department -",r[3])
print("Date Of Birth - ",r[4])
confirm=input("Do you want to delete the record(s) (y/n - )")
if confirm in("y",“Y"):
delst = "DELETE FROM EMP WHERE name=' "+senm+" ' "
mycur.execute(delst)
print("record Deleted")
mydb.commit()
else:
return
Employee Details Manipulation Using MySQL-Python
# Main File Operation Menu
while True:
print("\n\nMENU FOR DATA MANIPULATION")
print("1. INSERT NEW RECORDS")
print("2. DISPLAY ALL RECORDS")
print("3. SEARCH & DISPLAY")
print("4. COUNT & DISPLAY")
print("5. DELETE RECORD")
print("6. EDIT RECORD")
print("7. ARRANGE RECORDS IN ASCENDING & DESCENDING ORDER")
ch = int(input("\nEnter Your Choice (1-7) - "))
if ch == 1:
insert()
elif ch == 2:
showrecs()
elif ch==3:
print("\n*************************************")
ch1= int(input("1. SEARCH ON EMPLOYEE NO\n2. SEARCH ON NAME\nENTER YOUR
CHOICE(1/2) - "))
if ch1==1:
searcheno()
elif ch1==2:
searchname()
Employee Details Manipulation Using MySQL-Python
elif ch==4:
print("\n*************************************")
ch1 = int(input("1. COUNT RECORDS ON DEPARTMENT\n2. COUNT
RECORDS>=SALARY\nENTER YOUR CHOICE(1/2) - "))
if ch1==1:
countdept()
elif ch1==2:
countsal()
elif ch==5:
print("\n*************************************")
ch1 = int(input("1. DELETE RECORDS ON EMP NO\n2. DELETE RECORDS ON
NAME\nENTER YOUR CHOICE(1/2) - "))
if ch1==1:
deleno()
elif ch1==2:
delname()
elif ch == 6:
editsal_eno()
Employee Details Manipulation Using MySQL-Python
elif ch==7:
print("\n*************************************")
print("1. ARRANGE ON EMP NAME IN ASCENDING ORDER\n2. ARRANGE ON EMP
NAME IN DESCENDING ORDER\n")
print("3. ARRANGE ON EMP NAME IN ASCENDING ORDER\n4. ARRANGE ON EMP
NAME IN DESCENDING ORDER\n")
ch1=int(input("\nEnter Your Choice(1-4)- "))
if ch1 == 1:
show_name_asc()
elif ch1 == 2:
show_name_desc()
elif ch1==2:
show_salar_asc()
elif ch1==2:
show_salary_desc()
ans=input("\nWant to Continue with Data manipulation (y/n) - ")
mydb.close()
Book Details Manipulation Using MySQL-Python
Write a menu driven program using MySQL Database Connectivity to create database
BOOKDB and table BOOK. In addition to this, perform the following operations :
1. INSERT NEW RECORDS
2. DISPLAY ALL RECORDS Database name - bookdb
Table – Book
3. SEARCH & DISPLAY
Fields Data type
4. COUNT RECORDS BASED ON A CATEGORY Bookno int
5. COUNT RECORDS MORE THAN A PRICE Name varchar(25)
6. DELETE RECORD MATCHING WITH A BOOKNO Category varchar(10)
Price Decimal(10,2)
7. DELETE RECORD MATCHING WITH BOOKNAME
DOP date
8. EDIT PRICE OF A RECORD FOR A BOOKNO
Program :
import mysql.connector as sq
mydb=sq.connect(host="localhost",user="root“ , passwd=“student")
if mydb.is_connected():
print("connection done")
mcur=mydb.cursor()
try:
mcur.execute("CREATE DATABASE BOOKDB")
print("Database created")
except:
print("DATABASE already created")
Book Details Manipulation Using MySQL-Python
mcur.execute("USE BOOKDB")
try:
mcur.execute("CREATE TABLE BOOK(BOOKNO INT(3) PRIMARY KEY, BNAME VARCHAR(20),
CATEGORY VARCHAR(15), PRICE DECIMAL(7,2),DOP DATE)")
print("Table created")
except:
print("Table already created")

def insert():
while True:
bno=input("Enter book no:")
bn=input("Enter book name:")
cat=input("Enter category:")
pr=input("Enter price:")
dpur=input("Enter date of purchase:")
st="INSERT INTO BOOK VALUES("+bno+",' "+bn+" ',' "+cat+" ',"+pr+",' "+dpur+" ')"
mcur.execute(st)
ans=input("Do you want to continue y/Y:")
if ans in "nN":
break
mydb.commit()
Book Details Manipulation Using MySQL-Python

def showrec(): def searchbno():


#Retrieving all records bno = input("Enter book no:")
mcur.execute("SELECT * FROM BOOK") mcur.execute("SELECT * FROM BOOK ")
rec=mcur.fetchall() rec=mcur.fetchall()
ctr=mcur.rowcount ctr = mcur.rowcount
for r in rec: f = 0:
print("bookno",r[0]) for r in rec:
print("bookname",r[1]) if r[0] == int(bno):
print("category",r[2]) print("bookname",r[1])
print("price",r[3]) print("category",r[2])
print("date of publishing",r[4]) print("price",r[3])
print("\nTotal records in the table -",ctr) print("date of publishing",r[4])
f =1
break
if f == 0
print(“No such record found”)
Book Details Manipulation Using MySQL-Python
def searchbname():
bn=input("Enter book name:")
mcur.execute("SELECT * FROM BOOK ")
rec=mcur.fetchall()
ctr=mcur.rowcount
if ctr==0:
print("Record not found")
else:
for r in rec:
if r[1]==bn:
print("bookno",r[0])
print("category",r[2])
print("price",r[3])
print("date of publishing",r[4])

def countcatg():
cat=input("Enter category:")
mcur.execute("SELECT * FROM BOOK WHERE CATEGORY='"+cat+"'")
rec=mcur.fetchall()
cnt=mcur.rowcount
print("Count of records with ",cat,"category:",cnt)
Book Details Manipulation Using MySQL-Python
def delbookno():
bno=input("Enter bookno")
str1="SELECT * FROM BOOK WHERE BOOKNO = "+bno+""
mcur.execute(str1)
def countpr(): rec=mcur.fetchone()
pr=input("Enter price:") ctr=mcur.rowcount
st= "SELECT * FROM BOOK WHERE PRICE > "+pr+"" if ctr==0:
mcur.execute(st) print("Record not found")
rec=mcur.fetchall() else:
cnt=mcur.rowcount print("bookno",rec[0])
print(“No. of records with price > ",pr,"is:",cnt) print("bookname",rec[1])
print("category",rec[2])
print("price",rec[3])
print("date of publishing",rec[4])
ans=input("want to delete thisrecord?y/n")
if ans in "yY":
str2="DELETE FROM BOOK WHERE BOOKNO ="+bno+“ "
mcur.execute(str2)
mydb.commit()
Book Details Manipulation Using MySQL-Python
def delname():
bn=input("Enter book name:")
mcur.execute("SELECT * FROM BOOK WHERE BNAME='"+bn+"'")
rec = mcur.fetchall()
ctr = mcur.rowcount
if ctr == 0:
print("Record not found")
else:
for r in rec:
print("bookno",r[0])
print("bookname",r[1])
print("category",r[2])
print("price",r[3])
print("date of publishing",r[4])
ans=input("Do you want to delete the records?y/n")
if ans in "yY":
str2="DELETE FROM BOOK WHERE BNAME ='"+bn+"'"
mcur.execute(str2)
mydb.commit()
Book Details Manipulation Using MySQL-Python
def editbno():
bno=input("Enter bookno")
str1="SELECT * FROM BOOK WHERE BOOKNO ="+bno+""
mcur.execute(str1)
rec=mcur.fetchone()
ctr=mcur.rowcount
if ctr==0:
print("Record not found")
else:
print("bookno",rec[0])
print("bookname",rec[1])
print("category",rec[2])
print("price",rec[3])
print("date of publishing",rec[4])
ans=input("Do you want to edit this record?y/n")
if ans in "yY":
pr=input("Enter new price")
str2="UPDATE BOOK SET PRICE="+pr+" WHERE BOOKNO ="+bno+""
mcur.execute(str2)
mydb.commit()
Book Details Manipulation Using MySQL-Python
while True:
print("\n\nMENU FOR DATA MANIPULATION")
print("1. INSERT NEW RECORDS")
print("2. DISPLAY AND COUNT ALL RECORDS")
print("3. SEARCH & DISPLAY")
print("4. COUNT RECORDS BASED ON A CATEGORY")
print("5. COUNT RECORDS MORE THAN A PRICE")
print("6. DELETE RECORD MATCHING WITH A BOOKNO")
print("7. DELETE RECORD MATCHING WITH BOOKNAME")
print("8: EDIT PRICE OF A RECORD FOR A BOOKNO")
ch = int(input("\nEnter Your Choice (1-8) - "))
if ch == 1:
insert()
elif ch == 2:
showrec()
elif ch==3:
ch1= int(input("1. SEARCH ON BOOK NO\n2. SEARCH ON BOOKNAME\nENTER YOUR
CHOICE(1/2) - "))
if ch1==1:
searchbno()
elif ch1==2:
searchbname()
Book Details Manipulation Using MySQL-Python
elif ch==4:
countcatg()
elif ch==5:
countpr()
elif ch==6:
delbookno()
elif ch==7:
delname()
elif ch==8:
editbno()
ans=input("\nWant to Continue with Data manipulation (y/n) - ")
if ans in "nN":
break
mcur.close()
mydb.close()
MySQL-Python Connectivity Terminology
 import mysql.connector
This line imports the MySQL Connector Python module in your program so
the Program can use module’s API to connect MySQL.
 mysql.connector.connect()
This method established a connection to the MySQL database from
Python application and returned a MySQL Connection object which
can be used to perform various operations on the MySQL
Database.
 connection.is_connected()
Is_connected() is the method of the MySQLConnection class through it
can be verified that wheter python application is connected to MySQL
or not.
connection.cursor()
 execute()
This method executes the SQL query and returns a Result Set object
which contains all the rows when the query returns any records from
MySQL .
 commit() method to make sure that the commands detailed in the DML
command are implemented in the database.
MySQL-Python Connectivity Terminology
 cursor.close()
Using the cursor’s close method the cursor object can be closed. Once the
cursor object is closed noSQL statement can not executed.
 connection.close()
MySQL database connection can be closed using the close() method of
Connection class
 cursor.fetchall()
Fetch() method fetch all the records present in the result set.
 cursor.fetchone()
cursor.fetchone() method is used to fetch single row from the result set.
 cursor.fetchmany(n)
cursor.fetchmany(n) method is used to fetch n number of rows from the
result set.
 cursor.close()
Using the cursor’s close method the cursor object can be closed. Once the
cursor object is closed noSQL statement can not executed.
 connection.close()
MySQL database connection can be closed using the close() method of
Connection class
Assessment
Answer the following
Write the statement required to incorporate MySQL interface with Python
Answer : import mysql.connector

Which method is used to create the connection object in Python


Answer : connect()

What is the Python database interface known as?


Answer : DB-API (Database – Application Programming Interface)

____________ refers to the logical set of records that is fetched from the database
Answer : ResultSet

____________ method will return only one record from the resultset
Answer : fetchone

____________ is a control structure that allows record by record processing of records in


the result set
Answer : cursor
Assessment
Answer the following
__________ property of _______ object returns the number of records fetched from the
database
Answer : rowcount, cursor

_________ method invoked through ________ object is used to create the cursor object in
Python
Answer : cursor(), connection object

To check the whether the connection is successful or not _______ method can be used
Answer : is_connected()

A resultset is extracted from the database using the cursor object (that has been already
created) by giving the following statement.
Mydata=cursor.fetchone()
(a) How many records will be returned by fetchone() method?
(b) What will be the datatype of Mydata object after the given command is
executed?
Answer : (a) One record (b) tuple
Assessment
Answer the following
__________________________ #i. query to extract all records from table book
__________________________ #ii. statement to return all records to the result set
__________________________ #iii. statement to get no. of records into an object recs
for r in recs:
print(r[0],r[1],r[2],r[3],sep = "\t")
print("\nTotal records in the table -",ctr)
(a) Fill in the blanks for i, ii and iii
Answer : mycur.execute("SELECT * FROM EMP")
recs = mycur.fetchall()
ctr = mycur.rowcount
(b) What will be the datatype of recs and r objects after the given command is
executed?
Answer : recs - list object
r - tuple object

You might also like