Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import psycopg2
  4.  
  5. class database(object):
  6. def __init__(self,database,table):
  7. self.database = database
  8. self.table = table
  9. self.sql_do('create table if not exists '+self.table+' ( key TEXT,data TEXT)')
  10. def sql_do(self, sql, *params):
  11. self._db.execute(sql, params)
  12. self._conn.commit()
  13. def insert(self, row):
  14. # if data is string so use '{}' instead of {} , because the portgres wants "hello" not hello
  15. #print('insert into public.{} (key, data) values ({}, {})'.format(self._table,row['key'], row['data']))
  16. self._db.execute('insert into public.{} (key, data) values ({}, {})'.format(self._table,row['key'], row['data']))
  17. self._conn.commit()
  18. def retrieve(self, key):
  19. cursor = self._db.execute('select key,data from {} where key = {}'.format(self._table,key))
  20. return dict(cursor.fetchone())
  21. def update(self, row):
  22. self._db.execute('update {} set data={} where key = {}'.format(self._table,row['data'],row['key']))
  23. self._conn.commit()
  24. def delete(self, key):
  25. self._db.execute('delete from {} where key = {}'.format(self._table,key))
  26. self._conn.commit()
  27.  
  28.  
  29.  
  30.  
  31. def __iter__(self):
  32. self._db.execute('select * from {} '.format(self._table))
  33. for row in self._db:
  34. yield row
  35. @property
  36. def database(self):
  37. return self.database
  38. @database.setter
  39. def database(self, fn):
  40. self._database = fn
  41. self._conn = psycopg2.connect(database = fn, user = "postgres", password = "moazam@123", host = "127.0.0.1", port = "5432")
  42. self._db =self._conn.cursor()
  43. print('#'*3 + " connected to database " +fn+' '+'#'*3)
  44. @database.deleter
  45. def database(self):
  46. self.close()
  47. @property
  48. def table(self):
  49. return self._table
  50. @table.setter
  51. def table(self, t):
  52. self._table = t
  53. def close(self):
  54. self._db.close()
  55. if __name__ == '__main__':
  56. d=database(database='sample_db',table='test')
  57. d.insert({"key": 1,"data": 10})
  58. for i in d:
  59. print(i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement