Interface Python With MySQL
Interface Python With MySQL
Final Program
1. import mysql.connector
2. con = mysql.connector.connect(host= ‘localhost’,username = ‘root’,
password= ‘test123’ , database = ‘test_db’) #here database param is
optional if passed then directly connect to that particular db
3. cur = con.cursor() #calling cursor function over connection object
4. cur.exeute(“select * from employee”)
5. data = cur.fetchall()
6. print(data) # returns list of tuples
7. print(type(data)) #return List
8. conn.commit() # call this if needs to do any change in database
9. for d in data :
10. print(d[0]) #print 0 index or first attribute of the table
11. cur.rowcount # returns the no of rows fetched
Parameterized Query
It is used when needs to pass the data from the user
1) sql_query = “select * fom employee where name like ‘%s’”
conn.execute(sql_query,(‘Ram’,)) #incase of single value tuple need to give
comma
Questions 1)
Question 2)
Question 3)
Ques 4) To establish a connection between python & SQL database connect() is used. Which of the
following arguments may not be necessarily be given on calling connect() function ?
Ques 5)
Ques 6)
Ques 7)
Ques 8) A resuttset is extracted from the database using the cursor object (that has been already
created) by giving the following statement.
Mydata = cursor.fetchone()
Ques 9) Rahim wants to write a program in Python to insert the following record in the table named
Bank_Account in MySQL database, Bank : ·
Accno – integer
Cname – string
Atype – string
Amount – float
Note the following to establish connectivity between Python and MySQL : · Username – admin ·
Password – root · Host – localhost
The values of fields Accno, Cname, Atype and Amount have to be accepted from the user. Help
Rahim to write the program in Python.
Ques 10) Sangeeta wants to write a program in Python to delete the record of a candidate “Raman”
from the table named Placement in MySQL database, Agency:
The table Placement in MySQL contains the following attributes :
CName – String
Dept – String
Place – String
Salary – integer
Note the following to establish connectivity between Python and MySQL : · Username – root ·
Password – job · Host – localhost
Help Sangeeta to write the program in Python for the above mentioned task