Advertisement
DrAungWinHtut

exam_json_db.py

Jan 12th, 2024
694
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import json
  2. import mysql.connector
  3.  
  4. db_connection = mysql.connector.connect(
  5.     host = "localhost",
  6.     user = "root",
  7.     passwd = "",
  8.     database = "schooldb"
  9. )
  10.  
  11. found = False
  12.  
  13. # no error!
  14. print('Database is connected successfully!')
  15.  
  16. mycursor = db_connection.cursor()
  17.  
  18. mycursor = db_connection.cursor()
  19. mycursor.execute("CREATE TABLE  IF NOT EXISTS examtb(id int primary key auto_increment, question text not null, option1 text not null, option2 text not null, option3 text not null, correct_ans text not null)")
  20.  
  21.  
  22. mycursor.execute("SHOW TABLES")
  23. for row in mycursor:
  24.     #print(row)
  25.     if row[0] == 'examtb':
  26.         print('Table created successfully')
  27.         found = True
  28.  
  29. if not found:
  30.     print('Table creation fails')
  31.     exit(1)
  32.  
  33. with open('q.json','r') as qfile:
  34.     questions = json.load(qfile)
  35.     for quest in questions:        
  36.         sql = "INSERT INTO examtb(question,option1,option2,option3,correct_ans) values (%s,%s,%s,%s,%s)"
  37.         params = (quest['question'],quest['option1'],quest['option2'],quest['option3'],quest['correct_ans'])
  38.         mycursor.execute(sql,params)
  39.         db_connection.commit()
  40.  
  41.  
  42.  
  43.  
  44. mycursor.execute("SELECT * FROM examtb")
  45. for row in mycursor:
  46.     print(row)
  47.  
  48.  
  49.  
  50. mycursor.close()
  51. db_connection.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement