0% found this document useful (0 votes)
138 views

CH 8-Interfacing Python With Mysql (Connectivity) For Board Exam

Hi

Uploaded by

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

CH 8-Interfacing Python With Mysql (Connectivity) For Board Exam

Hi

Uploaded by

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

CHAPTER – 8

(INTERFACING PYTHON WITH MYSQL)


PRACTICE QUESIONS
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) 1 (d) 0
5. The ………. creates a connection to the MySQL server and
returns aConnection object.
(a) connect() (b) connection()
(c) connector() (d) None of the 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
connect() method.
(a) 2 (b) 3 (c) 4 (d) 5
9. To establish the Python-MySQL connection, connect()
method is used with certain parameters or arguments.
Which of the following is nota 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 methodshould 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)executemanyc) executealld)executeQ


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 theconnection 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 = mycon.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 inthe database permanently.
(a) done() (b) commit() (c) reflect() (d) final()
25. Which function retrieve all (remaining) rows of a query
result an return themin 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 Nonewhen no more data is available
(b) Fetch the First row of a query result set, returning a
single tuple, or Nonewhen no more data is available
(c) Fetch the current row of a query result set, returning a
single tuple, or Nonewhen 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( )
2 - MARKS
THEORY
1. What is 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 is the role of execute ()?
5. What are the steps for creating database connectivity
applications?
6. What is a result set?
7. What is a database cursor?
8. Write the difference between fetchone() and fetchmany().
9. Write the difference between fetchmany() and fetchall().
10. Write the return type of fetchone() and fetchall().
11. What is the role of cursor.rowcount?
CASE STUDY BASED 2 - MARKS
12. 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
13. 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()

14. 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()
15. Consider the following information stored in the
table: EMP
ENO ENAME DEPT SALARY
1 ALEX MUSIC 60000
2 PETER ART 67000
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)

16. Consider the below given SCHOOL table and predict the
output of Python program based on this table:
17. Consider the below given LOCATION table and predict the
output of Python program based on this table:

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. Consider the date format to be
'YYYY-MM-DD'
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. Program to update the salaries of all employees who have
salary less than 80000 in “office”database of MySQL. (table
name : emp, password=‟ggsss‟)The given program is used to
connect with MySQL abd show the name of the allthe
record from the table “stmaster” from the database
“oraclenk”. Write the missingstatements to complete the
code.
import _____.connector_______ pymysql
dbcon=pymysql._____________(host="localhost",
user=”root”, ________="sia@1928",
database="oraclenk")
if dbcon.isconnected()==False:
print(“Error in establishing connection:”)
cur=dbcon.______________()
query= “select * from stmaster”
cur.execute(_________)
resultset=cur.fetchmany(3)

for row in resultset:


print(row)
dbcon.______()
4. Write the following missing statements to complete the code:
import mysql.connector as mysql
defsql_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 :: ")
querry="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.
5. Write the following missing statements to complete the code:
Statement 1 – To form the cursor object
Statement 2 – To execute the query that extracts records of
those employees having salary more than
25000.
Statement 3- To read the complete result of the query
(records whose salary is more than 25000)
into the object named data, from the table
EMP in the database.
import mysql.connector as mysql
defsql_data():
conn=mysql.connect(host="localhost",user="root",
password="tiger", database="company")
mycursor=__________ #Statement 1
print("Employees with salary more than 25000 are:")
try:
______________#Statement 2
resultset= ___________#Statement 3
for row in resultset:
print(row)
except:
print("Error: unable to fetch data")
conn.close()
6. Write the missing statement to complete the code.
Statement 1 – To check whether connection is not
established.
Statement 2 – To create cursor object.
Statement 3 – To retrieve all the data from the cursor
object.
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",

password="1",database="stu")
if______________ # Statement 1
print("Error connecting to MYSQL DATABASE")
________________ # Statement 2
c.execute("select * from student where marks>80 and
marks<90")
_____________ # Statement 3
count=c.rowcount
print("total no of rows:",count)
for row in r:
print(row)
7. Consider the following Python code is written to access the
details of employee, whose employee number is given:
Complete the missing statements:
Statement 1 – To create a cursor object to execute the
query.
Statement 2 – To execute the query stored in the variable
change.
Statement 3 – To make the changes in the database
physically.
def Search():
import mysql.connector
mydb=mysql.connector.connect(host="localhost",
user="root",passwd="sys",database="DB")
_______________ # Statement 1
change="update employee set salary=salary+5000 where
empno= 1011"
_______________ # Statement 2
______________ # Statement 3
results = mycursor.fetchall()
print(results)
8. You are required to complete the statements so that the
code can be executed properly.
import mysql.connector
db=mysql.connector.________(i) fill the statement with
appropriate method.
(host='localhost',user='root',password='moahan')
cur=db.cursor( )
cur.execute("_______;") (ii) command to display all the
database name
print(cur.________) (iii) method to extract all the
required
from the cursor
9. You are required to complete the statements so that the
code can be executed properly.
import _______ (i) complete the statement with
appropriate library name
db=mysql.connector. __________(ii)
(host=”localhost”, user=”root”, password=”smsmb”)
(ii)-> # fill the statement with appropriate method
cur=db._________( ) (iii) # method to open the cursor
object
data= "______" (iv) #complete the statement with the
appropriate database name
cur.execute("________"+data) (v)
# command to open the
database
cur.execute("_____") (vi) #command to display name of all
the tables.

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

You might also like