Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mysql.connector
- from mysql.connector import Error
- def create_connection():
- try:
- conn = mysql.connector.connect(
- host="localhost", user="root", password="", database="quizdb"
- )
- if conn.is_connected():
- print("Connected to MySQL")
- return conn
- except Error as e:
- print(f"Error: {e}")
- return None
- def close_connection(conn):
- if conn.is_connected():
- conn.close()
- print("MySQL connection is closed")
- def create_quiz(conn, question, choices, correct_ans):
- try:
- query = (
- "INSERT INTO quiztb (question, choices, correct_ans) VALUES (%s, %s, %s)"
- )
- data = (question, choices, correct_ans)
- cursor = conn.cursor()
- cursor.execute(query, data)
- conn.commit()
- print("Quiz created successfully")
- except Error as e:
- print(f"Error: {e}")
- finally:
- cursor.close()
- def read_insert_quizdata(conn, filename):
- with open("questions.txt", "r") as file:
- lines = file.readlines()
- for line in lines:
- #print(line)
- question, choices, correct_answer = line.strip().split("#")
- create_quiz(conn, question, choices, correct_answer)
- print(f"All Quiz data from file {filename} inserted successfully")
- if __name__ == "__main__":
- conn = create_connection()
- if conn:
- read_insert_quizdata(conn, "question.txt")
- close_connection(conn)
- else:
- print("Connection failed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement