Computer Science - Class 12
Solutions to CBSE Sample Paper - Computer Science Class 12

(b) The code given below inserts the following record in the table Student:

RollNo – integer

Name – string

Clas – integer

Marks – integer

Note the following to establish connectivity between Python and MYSQL:

  • Username is root

  • Password is tiger

  • The table exists in a MYSQL database named school.

  • The details (RollNo, Name, Clas and Marks) are to

be accepted from the user.

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 Student.

Statement 3- to add the record permanently in the databas

 

import mysql.connector as mysql

def sql_data():

con1=mysql.connect(host="localhost",user="root",

password="tiger", database="school")

mycursor=_________________ #Statement 1

rno=int(input("Enter Roll Number :: "))

name=input("Enter name :: ")

clas=int(input("Enter class :: "))

marks=int(input("Enter Marks :: "))

querry="insert into student

values({},'{}',{},{})".format(rno,name,clas,marks)

______________________ #Statement 2

______________________ # Statement 3

print("Data Added successfully")

 

Answer:

import mysql.connector as mysql

def sql_data():

    con1=mysql.connect(host="localhost",user="root", password="tiger", database="school")

    mycursor=con1.cursor() #Statement 1

    rno=int(input("Enter Roll Number :: "))

    name=input("Enter name :: ")

    clas=int(input("Enter class :: "))

marks=int(input("Enter Marks :: "))

querry="insert into student values({},'{}',{},{})".format(rno,name,clas,marks)

    mycursor.execute(querry) #Statement 2

    con1.commit() # Statement 3

    print("Data Added successfully")

 

Explanation:

Statement 1: To form the cursor object, the cursor( ) method is used.

          Syntax: cursor_object=connection_object.cursor( )

Statement 2: To execute a MySQL command, the execute( ) method is used.

          Syntax: cursor_object.execute(“MySQL query”/query_string)

Statement 3: To add a record permanently to the database, the commit( ) method is used.

                       Syntax: connection_object.commit( )

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.