Test Index
Interface of Python with SQL Database
© examsnet.com
Question : 5 of 10
Marks:
+1,
-0
(A) (i) Define cartesian product with respect to RDBMS.(ii) Sunil wants to write a program in Python to update the quantity to 20 of the records whose item code is 111 in the table named
shop in MySQL database named Keeper.The table shop in MySQL contains the following attributes :• Item_code : Item code (Integer)• Item_name : Name of item (String)• Qty : Quantity of item (Integer)• Price : Price of item (Integer)Consider the following to establish connectivity between Python and MySQL :• Username : admin• Password : Shopping• Host : localhostOR(B) (i) Give any two features of SQL.(ii) Sumit wants to write a code in Python to display all the details of the passengers from the table flight in MySQL database, Travel. The table contains the following attributes :F_code : Flight code (String)F_name : Name of flight (String)Source : Departure city of flight (String)Destination : Destination city of flight (String)Consider the following to establish connectivity between Python and MySQL :• Username : root• Password : airplane• Host : localhost[CBSE 2024 Set 4]
Solution:
(A)(i)The Cartesian product (cross join) of two relations combines every row (tuple) of the first relation with every row of the second, giving all possible pairs of rows. It is denoted by X. If the relations have m and n rows (and p and q columns), the result has m × n rows (and p + q columns).(A)(ii)
import mysql.connectormycon = mysql.connector.connect(host="localhost", user="admin", passwd="Shopping", database="Keeper")cursor = mycon.cursor()query = "UPDATE shop SET Qty = 20 WHERE Item_code = 111"cursor.execute(query)mycon.commit() # save the change permanentlymycon.close()Key point: After an
UPDATE (or INSERT/DELETE), commit() must be called; otherwise the change is not saved in the database.OR (B)(i)Two features of SQL:1. It is a non-procedural (declarative) language: we state what data is wanted, not how to get it.2. It provides commands both to define the structure of tables (DDL, e.g. CREATE, ALTER) and to work with the data (DML, e.g. INSERT, UPDATE, SELECT).(Also: SQL keywords are not case-sensitive; a statement ends with a semicolon.)OR (B)(ii)import mysql.connectormycon = mysql.connector.connect(host="localhost", user="root", passwd="airplane", database="Travel")cursor = mycon.cursor()cursor.execute("SELECT * FROM flight")data = cursor.fetchall() # list of all rows (tuples)for row in data: print(row)mycon.close()Explanation: fetchall() returns all the rows of the result as a list of tuples, and the loop displays each row.© examsnet.com
Go to Question: