Advertisement
DrAungWinHtut

savequizdb.py

Jan 19th, 2025
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. import mysql.connector
  2. from mysql.connector import Error
  3.  
  4.  
  5. def create_connection():
  6.     try:
  7.         conn = mysql.connector.connect(
  8.             host="localhost", user="root", password="", database="quizdb"
  9.         )
  10.         if conn.is_connected():
  11.             print("Connected to MySQL")
  12.             return conn
  13.     except Error as e:
  14.         print(f"Error: {e}")
  15.         return None
  16.  
  17.  
  18. def close_connection(conn):
  19.     if conn.is_connected():
  20.         conn.close()
  21.         print("MySQL connection is closed")
  22.  
  23.  
  24. def create_quiz(conn, question, choices, correct_ans):
  25.     try:
  26.         query = (
  27.             "INSERT INTO quiztb (question, choices, correct_ans) VALUES (%s, %s, %s)"
  28.         )
  29.         data = (question, choices, correct_ans)
  30.         cursor = conn.cursor()
  31.         cursor.execute(query, data)
  32.         conn.commit()
  33.         print("Quiz created successfully")
  34.     except Error as e:
  35.         print(f"Error: {e}")
  36.     finally:
  37.         cursor.close()
  38.  
  39.  
  40. def read_insert_quizdata(conn, filename):
  41.     with open("questions.txt", "r") as file:
  42.         lines = file.readlines()
  43.         for line in lines:
  44.             #print(line)
  45.             question, choices, correct_answer = line.strip().split("#")
  46.             create_quiz(conn, question, choices, correct_answer)
  47.         print(f"All Quiz data from file {filename} inserted successfully")
  48.  
  49.  
  50. if __name__ == "__main__":
  51.     conn = create_connection()
  52.     if conn:
  53.         read_insert_quizdata(conn, "question.txt")
  54.         close_connection(conn)
  55.     else:
  56.         print("Connection failed")
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement