Advertisement
Guest User

Untitled

a guest
May 3rd, 2019
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Purpose: Connect to mysql database using config file.
  4. """
  5.  
  6. from __future__ import unicode_literals
  7. from __future__ import print_function
  8.  
  9. import configparser
  10. import mysql.connector
  11.  
  12. class DBConnection(object):
  13. """
  14. Connect to mysql using config.ini file.
  15. """
  16. config_file = 'config.ini'
  17.  
  18. def __init__(self, get_config_parser, env):
  19. self.env = env
  20. self.get_config_parser = get_config_parser
  21. self.host = self.get_config_parser[self.env]['host']
  22. self.user = self.get_config_parser[self.env]['user']
  23. self.password = self.get_config_parser[self.env]['password']
  24. self.database = self.get_config_parser[self.env]['database']
  25.  
  26. def show_data(self):
  27. """
  28. Connect to db using credentails.
  29. """
  30. try:
  31. conn = mysql.connector.connect(
  32. host=self.host, user=self.user, password=self.password, database=self.database)
  33. if conn.is_connected():
  34. print("Connected to db")
  35. cur = conn.cursor() # cursor object for executing SQL statements
  36. cur.execute("select * from exam")
  37. result = cur.fetchall()
  38. print(result)
  39.  
  40. else:
  41. print("Connection failed")
  42.  
  43. except mysql.connector.Error:
  44. print("Error in connection")
  45.  
  46. finally:
  47. conn.close()
  48. print("Connection close")
  49.  
  50.  
  51. def get_config():
  52. """
  53. Read file and parse
  54. """
  55. db_config = configparser.ConfigParser()
  56. db_config.read(DBConnection.config_file)
  57. return db_config
  58.  
  59. if __name__ == '__main__':
  60. DB = DBConnection(get_config(), 'dev')
  61. DB.show_data()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement