Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

MySQL Connectivity ShortNotes

Uploaded by

reyhana2202
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

MySQL Connectivity ShortNotes

Uploaded by

reyhana2202
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Chapter 16 – Interface Python with MySQL

In order to connect to a database from within Python, you need a library (mysql
connector) that provides connectivity functionality.

Steps for Creating Database Connectivity Applications:

There are mainly seven steps that must be followed in order to create a database
connectivity application.
Step 1 : Start Python.
Step 2 : Import the packages required for database programming.
Step 3 : Open a connection to database.
Step 4 : Create a cursor instance.
Step 5 : Execute a query.
Step 6 : Extract data from result set.
Step 7 : Clean up the environment.

Step 1. Start Python


- Start Python’s editor where you can create your Python scripts.

Step 2. Import mysql.connector Package


- First of all you need to import mysql.connector package in your Python scripts. For
this, write import command as shown below:
import mysql.connector
or
import mysql.connector as sql1

Step 3: Open a connection to database.


- The connect( ) function of mysql.connector establishes connection to a MySQL
database and requires four parameters, which are:
<connection-object> = mysql.connector.connect(host = <host-name> , user =
<username> , passwd = <password> , database = <database>)

Eg:
Con1= mysql.connector.connect(host = “localhost” , user = “root” , passwd = “MyPass”
, database = “Test”)

The above command will establish connection to MySQL database with user as “root”,
password as “MyPass” and to the MySQL database namely Test which exists on the
MySQL.
- You can also check for successful connection using function is_connected( ) with
connected object, which returns True , if connection is successful.
Eg:
Con1.is_connected()
Step 4 : Create a cursor instance.
- When we connect to a database from within a script/program, then the query gets
sent to the server, where it gets executed, and the resultset (the set of records retrieved
as per query) is sent over the connection to you, in one burst of activity, i.e. in one go.
And in order to do the processing of data row by row, a special control structure is
used, which is called Database Cursor.
Syntax:
<cursorobject> = <connectedobject>.cursor( )
Eg:
Cursor1=Con1.cursor()

Step 5 : Execute a query


- Once you have created a cursor, you can execute SQL query using execute( ) function
with cursor object as per following syntax:
<cursorobject>.execute(<sql query string>)
- E.g.
Cur1.execute(“select * from customer”)
The above code will execute the given SQL query and store the retrieved records(i.e. ,
the resultset) in the cursor object (namely cursor) which you can then use in your
program/scripts as required.

Step 6 : Extract data from result set.


- Once the result of query is available in the form of a resultset stored in a cursor object,
you can extract data from the resultset using any of the following fetch( ) functions.
(i) <data>= <cursor>.fetchall( ) - It will return all the records retrieved as per query in a
tuple form.
(ii) <data> = <cursor>.fetchone( ) - It will return one record from the result set as a tuple
or a list. First time it will return the first record, next time it will fetch the next record
and so on.
This method returns one record as a tuple : if there are no more records then it returns
None.
(iii) <data>=<cursor>.fetchmany(<n>) - This method accepts number of records to
fetch and returns a tuple where each record itself is a tuple.
(iv) <variable>=<cursor>.rowcount – The rowcount is a property of cursor object that
returns the number of rows retrieved from the cursor so far.
For Example,
(i) The fetchall( ) method – fetch all the records.
(ii)The fetchone( ) method – fetch one record at a time.

Step 7: Clean up the Environment


- In this final step, you need to close the connection established. This you can do as
follows:
<connection object>.close( )
- E.g.
mycon.close( )

Consider the following table student:

c1=mysql.connector.connect(host="localhost",user="root",passwd="mysql",database="s
chool")
if c1.is_connected():
print("Successfully connected...")

Output:

Successfully connected...

fetchall()

cur1=c1.cursor()
cur1.execute("select * from student")
data=cur1.fetchall()
count=cur1.rowcount
print("Total Records = ", count)

Output:
Total Records = 5

for row in data:


print(row)

Output:
(3, 'ashok', 'xii c', 76.3)
(8, 'dia', 'xii b', 70.0)
(15, 'kannan', 'xii b', 90.3)
(18, 'viswa', 'xii c', 89.5)
(25, 'suganya', 'xii c', 76.0)

fetchmany():

cur2=c1.cursor()
cur2.execute("select * from student")
data=cur2.fetchmany(3)
for row in data:
print(row)

Output:

(3, 'ashok', 'xii c', 76.3)


(8, 'dia', 'xii b', 70.0)
(15, 'kannan', 'xii b', 90.3)

Update Operation:

sql1="update student set avg={} where rno={}".format(90,8)


cur3.execute(sql1)
c1.commit()
cur4=c1.cursor()
sql2="select * from student"
cur4.execute(sql2)
for row in cur4:
print(row)

Output:

(3, 'ashok', 'xii c', 76.3)


(8, 'dia', 'xii b', 90.0)
(15, 'kannan', 'xii b', 90.3)
(18, 'viswa', 'xii c', 89.5)
(25, 'suganya', 'xii c', 76.0)
Delete Operation

cur5=c1.cursor()
sql4="delete from student where rno={}".format(3)
cur5.execute(sql4)
sql5="select * from student"
cur5.execute(sql5)
for row in cur5:
print(row)

Output:

(8, 'dia', 'xii b', 90.0)


(15, 'kannan', 'xii b', 90.3)
(18, 'viswa', 'xii c', 89.5)
(25, 'suganya', 'xii c', 76.0)

Python-MySQL connectivity - Sample project coding:


import mysql.connector
def Menu():
c='y'
while(c=='y' or c=='Y'):
print("1. Add ")
print("2. Update ")
print("3. Delete ")
print("4. Display ")
print("5. Display all")
print("*. Quit ")
ch = int(input("Please Select ur choice? "))
if ch==1:
Add()
elif ch==2:
Update()
elif ch==3:
Delete()
elif ch==4:
Disp()
elif ch==5:
Dispall()
else:
print("Exit")
break
else:
print("You have entered an Invalid option!")
c=input("Do u want to continue (Y. Yes / N. No)? ")
def Disp():

db=mysql.connector.connect(host="localhost",user="root",password="mysql",database=
"school")
cursor=db.cursor()
srno=str(input("Enter Roll No of student to be searched? "))
cursor.execute("select * from student where rno ='"+srno+"'")
results = cursor.fetchall()
if cursor.rowcount !=0 :
for row in results:
print("Roll No = ", row[0] )
print("Name = ", row[1])
print("Class = ", row[2])
print("Average Mark = ", row[3], "\n")
else:
print("Student Record is not found...")

def Dispall():
try:

db=mysql.connector.connect(host="localhost",user="root",password="mysql",database=
"school")
cursor=db.cursor()
cursor.execute("select * from student")
results = cursor.fetchall()
print("Total No. of rows in Student Table = ",cursor.rowcount)
for row in results:
print("Roll No = ", row[0] )
print("Name = ", row[1])
print("Class = ", row[2])
print("Average Mark = ", row[3], "\n")
except:
print("Error! unable to fetch data")
def Add():
try:

db=mysql.connector.connect(host="localhost",user="root",password="mysql",database=
"school")
cursor=db.cursor()
trno=int(input("Enter the RollNo ? "))
tname=input("Enter the Name ? ")
tclass=input("Enter the Class ? ")
tavg=eval(input("Enter the Average ? "))
record=(trno,tname,tclass,tavg)
sql="Insert into student values (%s,%s,%s,%s)"
cursor.execute(sql,record)
db.commit()
print("Record is added successfully...")
except mysql.connector.Error as error:
print("Error! unable to Add new record...",error)
def Update():

db=mysql.connector.connect(host="localhost",user="root",password="mysql",database=
"school")
cursor=db.cursor()
urno=int(input("Enter Roll number of the student whose marks to be updated? "))
uavg=eval(input("Enter the new average? "))
cursor.execute("update student set avg = '"+str(uavg)+"' where rno='"+str(urno)+"'")
db.commit()
c=cursor.rowcount
if(c==0):
print("Update Error! Record not exist...")
cursor.close()
def Delete():

db=mysql.connector.connect(host="localhost",user="root",password="mysql",database=
"school")
cursor=db.cursor()
drno=str(input("Enter Roll number of the student whose details to be deleted? "))
cursor.execute("Delete from student where rno = '"+str(drno)+"'")
db.commit()
c=cursor.rowcount
if(c==0):
print("Delete Error! Record not exist...")
cursor.close()
Menu()

You might also like