MySQL Connectivity ShortNotes
MySQL Connectivity ShortNotes
In order to connect to a database from within Python, you need a library (mysql
connector) that provides connectivity functionality.
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.
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()
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
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:
Update Operation:
Output:
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:
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()