Advertisement
Guest User

Untitled

a guest
Mar 16th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. #!/usr/bin/python
  2. import MySQLdb
  3.  
  4. class Database:
  5.  
  6. host = 'localhost'
  7. user = 'root'
  8. password = '123'
  9. db = 'test'
  10.  
  11. def __init__(self):
  12. self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
  13. self.cursor = self.connection.cursor()
  14.  
  15. def insert(self, query):
  16. try:
  17. self.cursor.execute(query)
  18. self.connection.commit()
  19. except:
  20. self.connection.rollback()
  21.  
  22.  
  23.  
  24. def query(self, query):
  25. cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
  26. cursor.execute(query)
  27.  
  28. return cursor.fetchall()
  29.  
  30. def __del__(self):
  31. self.connection.close()
  32.  
  33.  
  34. if __name__ == "__main__":
  35.  
  36. db = Database()
  37.  
  38. #CleanUp Operation
  39. del_query = "DELETE FROM basic_python_database"
  40. db.insert(del_query)
  41.  
  42. # Data Insert into the table
  43. query = """
  44. INSERT INTO basic_python_database
  45. (`name`, `age`)
  46. VALUES
  47. ('Mike', 21),
  48. ('Michael', 21),
  49. ('Imran', 21)
  50. """
  51.  
  52. # db.query(query)
  53. db.insert(query)
  54.  
  55. # Data retrieved from the table
  56. select_query = """
  57. SELECT * FROM basic_python_database
  58. WHERE age = 21
  59. """
  60.  
  61. people = db.query(select_query)
  62.  
  63. for person in people:
  64. print "Found %s " % person['name']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement