Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

CHAPTER – 8

(INTERFACING PYTHON WITH MYSQL)


PRACTICE QUESTIONS

THEORY QUESTIONS

1. Write the command to install MySQL connector?


2. Which package do we import in Python to establish my SQL
python connectivity?
3. What is the significance of using connect () function and
write its syntax.
4. What are the steps for creating database connectivity
applications?
5. What is a result set?
6. What is a database cursor?
7. Differentiate between the following and write its return
type:
(i) fetchone() and fetchall() (ii) fetchmay() and fetchall()
(iii) fetchone() and fetchmany()
8. What is the role of cursor.rowcount?

STATE TRUE OR FALSE


1. fetchone() return None when no more data is available.
2. We always get same result from the methods fetch() and
fetchall().
3. rowcount is not a read-only attribute.
4. close() method is used to disconnect database connection.
5. Once a database connection is established, we are ready to
create tablesusing execute method of the created cursor.
6. rowcount is a read-only attribute.
7. The next row of resultset is fetched via fetchone().
8. We cannot create a new database using python MySql interface.
9. When we execute a MySql insert query in python, The new row
gets saved in thedatabase.
10. We cannot delete a mysql row using python program
ASSERTION & REASONING
1. A: Mr.Raj had taken a variable as a connection
object and used connect() function with MySQL. database
specification like hostname, username, password or
passwd and database itself. But connection could not
establish.
R: To use connect( ) function user must include or import
mysql.connector in the beginning of the program.

2. A: mydb = mysql.connector.connect
(host="192.68.45.251",user="you",
password="y")
R: host variable should be initialized with value
‘localhost’
3. A:mydb = mysql.connector.connect(
host="178.23.45.262", user="you",password="y")
R: database name has not been provided in the
connect function call.
4. A:con= # Assume connection is already created
data = [('Jane', 'F'),('Joe', 'M'),('John', 'M'),]
cur=con.cursor()
stmt= "INSERT INTO employees (fname, hire_date)
VALUES (%s, %s)"
cur.execute(stmt, data)
mydb.commit()
R: execute function can’t be used to insert multiple
rows.
5. A: An user run the following command to input a new
record in the table cur.execute("insert into students
values(1,'Anu',78.50,'B1'") but he found that record
cannot be inserted in the table .
R: Commit() function must used to save the changes
and reflect the data in the table.
6. A: To retrieve Three(3) students details we use
cursor.fetchmany(3) function.
R: The number of rows is a compulsory parameter for
cursor.fetchmany( 3)
7. A: To create a table in MySQL, use the "CREATE
TABLE"statement.
R: We can use cursor.run() to create the table.
8. A:mydb = mysql.connector.connect( host="localhost",
user="you",password="you")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
R: We can create a new database using execute
function.
9. A: cur.execute("DELETE FROM customers WHERE
address = "M")
R: Commit function should be called to save the
changes
10. A: The resultset refers to a logical set of records
that are fetched from the database by executing
an SQL query.
R: Result set stored in a cursor object can be
extracted by using fetch(…) functions
OBJECTIVE TYPE QUESTIONS (MCQ)
1. Which of the following is the correct set of commands for installing
and importing mysql connector, respectively?
(a) pip install mysql.connector import mysql.connector
(b) pip install mysql-connector import mysql.connector
(c) pip install mysql-connector import mysql-connector
(d) pip install mysql.connector import mysql-connector
2. Which my sql driver you need to install for connection of Python
With MYSQL
(a) mysql-connector (b) mysql.connector
(c) mysql-connect (d) All of the above
3. Mandatory arguments required to connect any database from
Python are:
(a) Username, Password, Hostname, Database name, Port
(b) Username, Password, Hostname
(c) Username, Password, Hostname, Database Name
(d) Username, Password, Hostname, Port
4. What is the maximum number of parameters that can be accepted
by connect method.
(a) 2 (b) 3 (c) 4 (d) 0
5. The ............. creates a connection to the MySQL server and returns a
Connection object.
(a) connect() (b) connection() (c) connector() (d) None above
6. Python enables Python programs to access MySQL databases
(a) import mysql.connect (b) import mysql.connector
(c) import mysql.connection (d) None of the above
7. The -------------------- constructor creates a connection to the
MySQL server andreturns a MySQL Connection object.
(a) connect() (b) connection()
(c) mysqlconnect() (d) None of the above
8. Maximum how many parameters can be accepted by cursor()
method.
(a) 2 (b) 3 (c) 4 (d) 0
9. To establish the Python-MySQL connection, connect() method is
used with certain parameters or arguments. Which of the following
is not a parameter/argument used with connect () method?
(a) user (b) password (c) database (d) table
10. Choose the correct statement to connect database from Python
code, is host is "localhost", user= "root" the database is “School”
with no password .
(a) connect(host="localhost",user= "root",database =
"School")
(b) connect(host= "localhost",user= "sql",password=NAN,
database = "root")
(c) connect(host= "host",user= "root",password=np.nan,
database = "School")
(d) connect(host= "loca",user="School",password="",
database = "root")
11. It acts as middleware between MYDSQL database connection and
SQL query. (a) cursor (b) Table (c) Query (d) row
12. commit() is required to be used after the execution of certain
queries in Python-MySQL connectivity applications. Identify one
such MySQL command out of the following options:
(a) CREATE (b) INSERT (c) SELECT (d) DROP
13. While working on Python-MySQL connectivity, fetchall() method is
used to get data from table. The method fetchall() returns ?
(a) A list (b) A tuple (c) Tuple of Lists (d) List of Tuples
14. The method cursor() is used in Python-MySQL connectivity
applications. This method is a member of:
(a) sql module (b) pickle module
(c) csv module (d) database-connectivity module
15. To establish a connection between Python and SQL database,
connect () is used. Which of the following arguments may not
necessarily be given while calling
connect() ?
(a) host (b) database (c) user (d) password
16. Ramesh is trying to fetch only one record from result set at a time.
Which method should be used by him?
(a) fetchmany(b) fetchno(c) fetchone(d) fetchall
17. This is the Property of cursor object that returns the number of
rows fetched
a) fetchall() b) resultsetc) rowcountd) none of the above
18. Fill in the blank
data = [('Jane', 'F'),('Joe', 'M'),('John', 'M'),]
stmt = "INSERT INTO employees (first_name, hire_date)
VALUES (%s, %s)"
cursor. (stmt, data)

(a)execute (b)executemany (c) executeall (d)execute Q


19. If cur is a valid cursor what will be the output of the following
cur.execute("select * from student") #student table has
5 rows
print(mycursor.rowcount)
(a) 5 (b)0 (c) -1 (d) None
20. If "my" is a valid cursor what will be the output of the following
my.execute("select * from student") #student table has
5 rows
myresult = my.fetchmany(3)
print(my.rowcount)
(a) 5 (b)3 (c) -1 (d)None
21. SQL command is passed to which function to run after
establishment of the connection between python and database:
(a) cursor() (b) execute() (c) connection() (d) fetchall()
22. Which of the following function is used to close the connection
between python and database?
(a) cursor.close() (b) is.close()
(c) connection.close() (d) execute.close()
23. Read the following code and assume that all necessary files are
alreadyimported
con = sql.connect(host='localhost',user='root',
password='in',database = 'com')
Cursor = con.cursor()
Query = “Select * from empl”
Which will be the next statement to execute query?
(a) Cursor.query.excute() (b) Cursor.execute(Query)
(c) Query.execute() (d) execute(Query)
24. When we run <connection>. method, it reflect the
changes made in the database permanently.
(a) done() (b) commit() (c) reflect() (d) final()
25. Which function retrieve all (remaining) rows of a query result an
return them in a list of tuples
(a) fetchone() (b) fetchall()(c) fetchmany ()(d) All the above
26. Which is the correct statement about fetchone()
(a) Fetch the next row of a query result set, returning a
single tuple, or None when no more data is available
(b) Fetch the First row of a query result set, returning asingle
tuple, or None when no more data is available
(c) Fetch the current row of a query result set, returning a
single tuple, or None when no more data is available
(d) None of the above
27. What is the datatype of the row returned from a resultset using
fetchone() function?
(a) Tuple (b) List (c) String (d) Dictionary
28. What is the datatype of the row returned from a resultset using
fetchmany() function?
(a) Tuple (b) List (c) String (d) Dictionary
29. What is returned when we execute the function fetchone() but no
rows are available tofetch ?
(a) None (b) Empty Tuple (c) Empty List (d) Error
30. What is returned when we execute the function fetchall() but no
rows are available tofetch ?
(a) None (b) Empty Tuple (c) Empty List (d) Error
31. What is returned when we execute the function fetchmany() but no
rows are availableto fetch ?
(a) None (b) Empty Tuple (c) Empty List (d) Error
32. In order to open a connection with MySQL database from within
Python using mysql.connector package, function is used.
(a) open( ) (b) database( ) (c) connect( ) (d) connected( )
3- MARKS (MISSING STATEMTS)
1. Write the following missing statements to complete the code:
Statement 1 – To import the required modules and give
alias as "ms"
Statement 2 – To execute the query that extracts records
of those teachers whose year of retirement
is 2022.
Statement 3- To fetch all the data from the cursor
instance
import as #Statement 1
con1=ms.connect(host="localhost",user="root",
password="ks",database="sch")
mycursor= con1.cursor()
print("Teachers about to retire in 2022 are: ")
# Statement 2
data= # Statement 3
for i in data:
print(i)
print()
2. K.B. public school is managing student data in ‘student’ table in
‘school’ database. Write python code that connects to database
school and retrieve all the records and display total number of
students.
import mysql.connector
con=mysql.connector.connect( ) # write code to
#connect with mysqldatabase
cur=con. # write code to create a cursor
cur.execute(“Select * from student”)
records= # write code to fetch records from
cursor
count= #write code to count total number of
students record
print("Total number of records :", count)
con.close()
3. Write the following missing statements to complete the code:
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="abc",database='MY')
mycursor= con1.cursor()
#Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name: ")
Q="update student set marks=marks+5 where
RollNo={}".format(rno)
#Statement 2
# Statement 3
print("Data updated successfully")
Statement 1 – To open/activate the school database.
Statement 2 – To execute the command that updates the
record in the table Student.
Statement 3- To make the updation in the database
permanently.
4. import mysql.connector
connection = mysql.connector.connect(host='localhost',
database='Employee',
user='root',
password='tiger')
cursor= #STATEMENT 1
empid=int(input("enter Empid"))
name=input("enter name")
salary=float(input("ENTER SALARY"))
result = #STATEMENT 2
#STATEMENT 3
Write the following missing statements to complete the code:
Statement 1 – To form the cursor object
Statement 2 – To execute the command that inserts the
record in the table Employee.
Statement 3- To add the record permanently in the
database.
5. The code given below reads the following record from the table
named Employee and displays only those records who have Salary
greater than 25000:
import mysql.connector as my
con = mysql.connect(host='localhost',
database='Emp',user='root',password='tiger')
cursor= #STATEMENT 1
#STATEMENT 2
records = #STATEMENT 3
for row in records:
print("Empid",row[0], "name",row[1],end=" ")
print("salary",row[2],end=" ")
print()
Write the following missing statements to complete the code:
Statement 1 – To form the cursor object Statement
Statement 2 – To execute the query that extracts records of
those Employees who have salary greater than
25000.
Statement 3- To read the complete result of the query (records
whose salary greater than 25000) into the
object named records, from the table Employee
in the database.
6. A table named ITEM is created in a database STORE. It contains
the following columns:
- integer,Iname– string , Price – float, Discount – float
#Line 1
con1= mysql.connect(host='localhost', user = 'root', password
='tiger', database='STORE')
mycursor = con1. #Line 2
q = 'SELECT * FROM ITEM where Price > { }'.format(_ ) #Line3
mycursor.execute(q)
data = mycursor. #Line 4
for rec in data:
print(rec)
con1.close()
i. Complete line 1 to import the appropriate module.
ii. Complete Line 2 to create the cursor object
iii. Complete the query given in Line 3 to display details ofall
such items from the table ITEMS whose price is
More than 5000.
iv. Complete Line 4 to extract all the records.
4 MARKS
1. David wants to write a program in Python to insert the following
record in the table named "Student" in MYSQL database,
"SCHOOL":
Rno (Roll number )- integer Name - string
DOB (Date of birth) – Date Fee – float
Note: Username – root Password – tiger
Host – localhost
The values of fields Rno, name, DOB and Fee has to be accepted
from the user. Help David to write the program in Python.
2. Roja wants to write a program(s) in Python to perform the following
operations in the table named Books in MYSQL database, "SHOP":
The table contains the following field/column.
Bno - integer Bname- string Price – float DOP– Date
Author - String
Note the following to establish connectivity between Python and
MySQL: Username – root Password – root
Host – 192.160.1.2
Help Roja to write the program in Python for the following:
(i) Roja, now wants to display the records of Books whose
Date of Publish is between "2000-05-09 to 2001-11-23".
Help Roja to write the program in Python.
(ii) She wants to decrease the Books price by 7% whose
book price is more than 900 and Author is "Anu".
3. Ram wants to write a program in Python to create the following
table named “EMP” in MYSQL database, ORGANISATION:
Eno- integer , Ename - string, Edept -string,
Sal (salary)-integer
Note:
Username – root , Password – admin , Host - localhost
Help Ram to write the program in Python to Alter the above
table with new column named Bonus (int).
4. Maya has created a table named BOOK in MYSQL database,
LIBRARY
BNO - integer, B_name – string, Price –integer
Note:
Username – root, Password – writer, Host – localhost.
Maya, now wants to display the name (only name) of books whose
price is more than 250. Help Maya to write the program in Python.
CASE STUDY BASED 2 - MARKS
1. Avni is trying to connect Python with MySQL for her project. Help
her to write thepython statement on the following:-
(i) Name the library, which should be imported to connect
MySQL with Python.
(ii) Name the function, used to run SQL query in Python.
(iii) Write Python statement of connect function having
the arguments values as :
Host name :192.168.11.111
User : root
Password: Admin
Database : MYPROJECT
2. Rearrange the following steps in connecting SQL with python:
1. Create a database object, say mydb, using connect()
function by passing username and password.
2. Execute SQL statement using the created cursor objects(mycur).
3. Import the library mysql.connector
4. Create a cursor object, mycur, for the created database
object(mydb) for reserving a temporary work area in the
system memory for storing the part of the active
database.

3. For the following SQL table named PASSENGERS in a database


TRAVEL.

import mysql.connecotor as c
s=c.connect(host='localhost',user='a',password='a')
cur=c.cursor()
cur.execute('USE TRAVEL')
cur.execute("SELECT * FROM PASSENGERS")
Res=cur.fetchall()
for R in Res:
print(R[1])
s.close()
4. The books table of test database contains the records shown below
and Predict the output of the following code:

import mysql.connector as sqltor


conn = sqltor.connect (host = "localhost", user = "learner",
passwd = "fast",database = "test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM books")
row = cursor.fetchone()
while row is not None:
print (row)
row = cursor.fetchone()
5.

Consider the
ENO ENAME DEPT SALARY following
1 ALEX MUSIC 60000 information stored
2 PETER ART 67000 in the table: EMP
3 JOHNY MUSIC 65000
4 USHA ART 85000

#Assume all basic setup related to connection


and cursor creation is already done.
Q="SELECT * FROM EMP"
mycurosr.execute(Q)
res=mycursor.fetchone()
res=mycursor.fetchone()
res=mycursor.fetchone()
d=int(res[3])
print(d*3)

**********************************************************

You might also like