Computer Science
Write code to connect to a MySQL database namely School and then fetch all those records from table Student where grade is ' A' .
Python MySQL
5 Likes
Answer
Table Student of MySQL database School
rollno | name | marks | grade | section | project |
---|---|---|---|---|---|
101 | RUHANII | 76.8 | A | A | PENDING |
102 | GEOGRE | 71.2 | B | A | SUBMITTED |
103 | SIMRAN | 81.2 | A | B | EVALUATED |
104 | ALI | 61.2 | B | C | ASSIGNED |
105 | KUSHAL | 51.6 | C | C | EVALUATED |
106 | ARSIYA | 91.6 | A+ | B | SUBMITTED |
107 | RAUNAK | 32.5 | F | B | SUBMITTED |
import mysql.connector as mysql
db_con = mysql.connect(
host = "localhost",
user = "root",
password = "tiger",
database = "School"
)
cursor = db_con.cursor()
cursor.execute("SELECT * FROM Student WHERE grade = 'A'")
student_records = cursor.fetchall()
for student in student_records:
print(student)
db_con.close()
Output
(101, 'RUHANII', 76.8, 'A', 'A', 'PENDING')
(103, 'SIMRAN', 81.2, 'A', 'B', 'EVALUATED')
Answered By
3 Likes
Related Questions
Assertion. The cursor rowcount returns how many rows have been retrieved so far through fetch…() methods.
Reason. The number of rows in a resultset and the rowcount are always equal.
What are the steps to connect to a database from within a Python application ?
Predict the output of the following code :
import mysql.connector db = mysql.connector.connect(....) cursor = db.cursor() sql1 = "update category set name = '%s' WHERE ID = %s" % ('CSS',2) cursor.execute(sql1) db.commit() print("Rows affected:", cursor.rowcount) db.close()
Explain what the following query will do ?
import mysql.connector db = mysql.connector.connect(....) cursor = db.cursor() person_id = input("Enter required person id") lastname = input("Enter required lastname") db.execute("INSERT INTO staff (person_id, lastname) VALUES ({}, '{}')".format(person_id, lastname)) db.commit() db.close()