Advertisement
DrAungWinHtut

mysqlpythondb.py

Dec 20th, 2023
792
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. from myconnection import connect_to_mysql
  2.  
  3. def create_student(cursor, name, age):
  4.     query = "INSERT INTO students (name, age) VALUES (%s, %s)"
  5.     cursor.execute(query, (name, age))
  6.  
  7. def read_students(cursor):
  8.     query = "SELECT * FROM students"
  9.     cursor.execute(query)
  10.     return cursor.fetchall()
  11.  
  12. def update_student(cursor, student_id, new_name, new_age):
  13.     query = "UPDATE students SET name=%s, age=%s WHERE id=%s"
  14.     cursor.execute(query, (new_name, new_age, student_id))
  15.  
  16. def delete_student(cursor, student_id):
  17.     query = "DELETE FROM students WHERE id=%s"
  18.     cursor.execute(query, (student_id,))
  19.  
  20. def main():
  21.     config = {
  22.         "host": "127.0.0.1",
  23.         "user": "root",
  24.         "password": "12345678",
  25.         "database": "schooldb",
  26.     }
  27.  
  28.     cnx = connect_to_mysql(config, attempts=3)
  29.  
  30.     if cnx and cnx.is_connected():
  31.         with cnx.cursor() as cursor:
  32.             # Create a new student
  33.             create_student(cursor, "John Doe", 20)
  34.  
  35.             # Read all students
  36.             print("All students:")
  37.             students = read_students(cursor)
  38.             for student in students:
  39.                 print(student)
  40.  
  41.             # Update a student
  42.             update_student(cursor, 1, "Updated Name", 25)
  43.  
  44.             # Read all students after update
  45.             print("\nAll students after update:")
  46.             students = read_students(cursor)
  47.             for student in students:
  48.                 print(student)
  49.  
  50.             # Delete a student
  51.             delete_student(cursor, 1)
  52.  
  53.             # Read all students after delete
  54.             print("\nAll students after delete:")
  55.             students = read_students(cursor)
  56.             for student in students:
  57.                 print(student)
  58.  
  59.         cnx.commit()
  60.         cnx.close()
  61.     else:
  62.         print("Could not connect to the database")
  63.  
  64. if __name__ == "__main__":
  65.     main()
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement