SHARE
TWEET

Untitled

a guest May 25th, 2019 93 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import pymysql
  2. from pprint import pprint as pprint
  3. __author__ = "Liquidgenius"
  4.  
  5. class Query:
  6.  
  7.     def __init__(self, host, port, user, password, schema):
  8.         self.host = host
  9.         self.port = port
  10.         self.user = user
  11.         self.password = password
  12.         self.schema = schema
  13.         self.table_name = None
  14.         self.column_names = list()
  15.         self.query = None
  16.         self.results = None
  17.  
  18.     def _get_db(self):
  19.         db = (pymysql.connect(host=self.host,
  20.                               port=self.port,
  21.                               user=self.user,
  22.                               password=self.password,
  23.                               database=self.schema,
  24.                               charset="utf8"))
  25.         return db
  26.  
  27.     def table(self, table):
  28.         self.column_names = list()
  29.         self.table_name = table
  30.         return self
  31.  
  32.     def columns(self, cols):
  33.         if not isinstance(cols, list):
  34.             cols = [cols]
  35.         self.column_names = self.column_names + cols
  36.         return self
  37.  
  38.     def execute(self):
  39.         if (self.table_name is not None) and (len(self.column_names) > 0):
  40.             db = (pymysql.connect(host=self.host,
  41.                                   port=self.port,
  42.                                   user=self.user,
  43.                                   password=self.password,
  44.                                   database=self.schema,
  45.                                   charset="utf8"))
  46.             cursor = db.cursor()
  47.             cols = ', '.join(map(str, self.column_names))
  48.             sql = f"SELECT {cols} FROM {self.table_name}"
  49.             self.query = sql
  50.             cursor.execute(sql)
  51.             self.results = [item for item in cursor.fetchall()]
  52.             db.close()
  53.         return self.results
  54.  
  55. # MySQL Credentials
  56. host =
  57. port =
  58. user =
  59. password =
  60. schema =
  61.  
  62. # Instantiate the object
  63. q = Query(host, port, user, password, schema)
  64.  
  65. # Set parameters
  66. table = "a_database_table"
  67. cols = ["id", "created_at"]
  68.  
  69. # Execute with chained methods
  70. results = q.table(table).columns(cols).execute()
  71.  
  72. # Print results
  73. pprint(results)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top