fork download
  1. import mysql.connector
  2.  
  3. mycon = mysql.connector.connect(
  4. host='localhost',
  5. user='root',
  6. password='password',
  7. database='School')
  8.  
  9. if mycon.is_connected():
  10. print('Database connected')
  11.  
  12. cursor = mycon.cursor()
  13.  
  14. # Display all the records of students in ascending order of Name:
  15.  
  16. sql ="SELECT * FROM STUDENT ORDER BY Name"
  17. cursor.execute(sql)
  18. data = cursor.fetchall()
  19. print("Answer for a):")
  20.  
  21. for rec in data:
  22. print(rec)
  23.  
  24.  
  25. # Display the number of records whose name starts with 'D':
  26.  
  27. sql ="SELECT COUNT(*) FROM STUDENT WHERE Name LIKE
  28. 'D%'"
  29. cursor.execute(sql)
  30. count = cursor.fetchone()[0]
  31. print("The number of records whose name starts with 'D' is{count}")
  32.  
  33.  
  34. # Delete the record whose ID is 3
  35.  
  36. sql ="DELETE FROM STUDENT WHERE ID =3"
  37. cursor.execute(sql)
  38. mycon.commit()
  39. print("Record Deleted")
  40.  
  41. mycon.close()
  42.  
Success #stdin #stdout 0.03s 25764KB
stdin
Standard input is empty
stdout
import mysql.connector

mycon = mysql.connector.connect(
            host='localhost',
            user='root',
            password='password', 
            database='School')   

if  mycon.is_connected():
    print('Database connected')

cursor = mycon.cursor()

# Display all the records of students in ascending order of Name:

sql ="SELECT * FROM STUDENT ORDER BY Name"
cursor.execute(sql)
data = cursor.fetchall()
print("Answer for a):")

for rec in data: 
print(rec)


# Display the number of records whose name starts with 'D':

sql ="SELECT COUNT(*) FROM STUDENT WHERE Name LIKE 
         'D%'"
cursor.execute(sql)
count = cursor.fetchone()[0]
print("The number of records whose name starts with 'D' is{count}")


# Delete the record whose ID is 3

sql ="DELETE FROM STUDENT WHERE ID =3"
cursor.execute(sql)
mycon.commit()
print("Record Deleted")

mycon.close()