Test Index

Interface of Python with SQL Database Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 6 of 10
Marks: +1, -0
(a) (i) Define the term foreign key with respect to RDBMS.
(ii) 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.
OR
(b) (i) Give one difference between CHAR and VARCHAR datatype in MySQL.
(ii) 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.
[CBSE 2024 Compartment]
Solution:  
(a)(i)
Foreign key: An attribute (or set of attributes) of one relation whose values refer to the primary key of another relation. It links the two tables and keeps referential integrity: a foreign key value must exist in the referenced primary key or be NULL. Example: GCode in PLAYERS referring to GCode (primary key) of GAMES.
(a)(ii)
import mysql.connector as sqltor
mycon = sqltor.connect(host="localhost", user="root",
passwd="job", database="Agency")
cursor = mycon.cursor()
query = "DELETE FROM Placement WHERE CName = 'Raman'"
cursor.execute(query)
mycon.commit()
mycon.close()
Explanation: connect() opens the connection with the given host, user, password and database; cursor() creates the cursor; execute() runs the DELETE query; commit() makes the deletion permanent in the database.
OR (b)(i)
CHARVARCHAR
Fixed-length: CHAR(n) always uses n characters of storage; shorter values are padded with spaces.Variable-length: VARCHAR(n) uses only as many characters as the value has (up to n), so it saves space.
(b)(ii)
import mysql.connector as sqltor
mycon = sqltor.connect(host="localhost", user="admin",
passwd="root", database="Bank")
cursor = mycon.cursor()
Accno = int(input("Account number: "))
Cname = input("Customer name: ")
Atype = input("Account type: ")
Amount = float(input("Amount: "))
query = "INSERT INTO Bank_Account VALUES ({}, '{}', '{}', {})".format(Accno, Cname, Atype, Amount)
cursor.execute(query)
mycon.commit()
mycon.close()
Explanation: The four values are accepted from the user, placed into the INSERT query with format() (string values inside quotes), the query is executed through the cursor and commit() saves the new record.
© examsnet.com
Advertisements
Go to Question: