loading…
CBSE Class 12 · Computer Science (083)
CBSE Class 12 Computer Science interface of Python with MySQL: connect, insert, search, update and delete with mysql.connector — programs with output, fetchone/fetchall and commit explained.
Real mysql.connector code; outputs from running it against a test database with the same tables.
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", passwd="your_password", database="company")
cur = mydb.cursor()
cur.execute("SELECT EmpNo, Name, Salary FROM EMPLOYEE")
rows = cur.fetchall()
for row in rows:
print(row)
print("Total records:", cur.rowcount)
mydb.close()
(101, 'Aarav', 52000) (102, 'Diya', 61000) (103, 'Kabir', 45000) (104, 'Meera', 70000) (105, 'Rohan', 38000) (106, 'Sana', 58000) (107, 'Vikram', 64000) Total records: 7
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", passwd="your_password", database="company")
cur = mydb.cursor()
eno = int(input("Employee no: "))
name = input("Name: ")
sal = int(input("Salary: "))
query = "INSERT INTO EMPLOYEE (EmpNo, Name, Salary, DeptNo) VALUES (%s, %s, %s, %s)"
cur.execute(query, (eno, name, sal, 40))
mydb.commit()
print(cur.rowcount, "record inserted")
mydb.close()
Employee no: 109 Name: Ishaan Salary: 47000 1 record inserted
PyRun is not affiliated with CBSE. Questions are written in the board's style for practice; they are not past papers.