Test Index
Interface of Python with SQL Database
© 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 - StringDept - StringPlace - StringSalary - integerNote the following to establish connectivity between Python and MySQL :• Username –
root• Password – job• Host – localhostHelp 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 – floatNote the following to establish connectivity between Python and MySQL :• Username – admin• Password – root• Host – localhostThe 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)
(b)(ii)
import mysql.connector as sqltormycon = 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)| CHAR | VARCHAR |
| 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. |
import mysql.connector as sqltormycon = 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
Go to Question: