You are on page 1of 1

Python – mysql connectivity revision notes

Step1 - import mysql.connector as ms


mysql.connector is the module which needs to be imported so that we can use
it’s function connect() to create a connection object con1. It initializes the
driver between python and mysql with the four parameters ie. server host,
mysql user, password and database of mysql
Step 2 - con1=ms.connect(host="localhost", user="root", passwd="",
db="busdb")
to execute the sql queries, we need to create a cursor object which has the
execute() function. The cursor object is created with the help of cursor()
function that belongs to connection object con1
Step 3 - cur1=con1.cursor()
biid=int(input("Enter the bus id: "))
sql="select * from bus where bid=%s"
val=(biid,)
Step 4 - cur1.execute(sql,val)
Now, to retrieve the data collected in the cursor object cur1, the fetchall() or
fetchone() (which belongs to cursor object cur1) is used to store in a python
object.
Step 5
p=cur1.fetchall() # list of tuples
p=cur1.fetchone() # a tuple
if the sql query is a DML statement (insert/ delete/ update), then it is
compulsory to use commit()
Step 6 - con1.commit() to save the changes made in the database.
n=cur1.rowcount()
n will have the number of rows affected by the execute() function

You might also like