Advertisement
Guest User

Untitled

a guest
Jan 29th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. import pymysql.cursors
  2. import json
  3.  
  4. class SQLHandler():
  5.     def __init__(self):
  6.         self.connection = pymysql.connect(host='den1.mysql6.gear.host',
  7.                              user='nsfwgamemanager',
  8.                              password='Ur8z_?SWcl6z',
  9.                              db='nsfwgamemanager',
  10.                              charset='utf8mb4',
  11.                              cursorclass=pymysql.cursors.DictCursor)
  12.  
  13.     def create(self):
  14.         create_command=\
  15.         """
  16.         CREATE TABLE `pending_games` (
  17.           `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  18.           `data` json DEFAULT NULL,
  19.           PRIMARY KEY (`id`)
  20.         ) ENGINE=InnoDB;
  21.         """
  22.  
  23.         try:
  24.             with self.connection.cursor() as cursor:
  25.                 cursor.execute(create_command)
  26.  
  27.             # self.connection is not autocommit by default. So you must commit to save
  28.             # your changes.
  29.             self.connection.commit()
  30.  
  31.         finally:
  32.             self.connection.close()
  33.  
  34.     def add_game(self, json_):
  35.         try:
  36.             with self.connection.cursor() as cursor:
  37.                 # Create a new record
  38.                 sql = "INSERT INTO `pending_games` (`data`,) VALUES ({},)".format(str(json.dumps(json_)))
  39.                 cursor.execute(sql)
  40.  
  41.             # self.connection is not autocommit by default. So you must commit to save
  42.             # your changes.
  43.             self.connection.commit()
  44.         finally:
  45.             self.connection.close()
  46.  
  47.     def retrieve_json(self):
  48.         result = []
  49.         try:
  50.             with self.connection.cursor() as cursor:
  51.                 # Read a single record
  52.  
  53.                 sql = "SELECT `data` FROM `pending_games`"
  54.                 cursor.execute(sql)
  55.                 result = cursor.fetchall()
  56.         finally:
  57.             self.connection.close()
  58.         with open('pending_games.json', 'w', encoding="utf-8") as f:
  59.              f.write(json.dumps(result, indent=4, sort_keys=True))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement