Skip to content

Instantly share code, notes, and snippets.

@mzmmoazam
Last active September 24, 2017 15:45
Show Gist options
  • Save mzmmoazam/693169c43489b6efec151b3b5930de28 to your computer and use it in GitHub Desktop.
Save mzmmoazam/693169c43489b6efec151b3b5930de28 to your computer and use it in GitHub Desktop.
This is class implementation of the portgresql using python.
#!/usr/bin/python
import psycopg2
class database(object):
def __init__(self,database,table):
self.database = database
self.table = table
self.sql_do('create table if not exists '+self.table+' ( key TEXT,data TEXT)')
def sql_do(self, sql, *params):
self._db.execute(sql, params)
self._conn.commit()
def insert(self, row):
# if data is string so use '{}' instead of {} , because the portgres wants "hello" not hello
#print('insert into public.{} (key, data) values ({}, {})'.format(self._table,row['key'], row['data']))
self._db.execute('insert into public.{} (key, data) values ({}, {})'.format(self._table,row['key'], row['data']))
self._conn.commit()
def retrieve(self, key):
cursor = self._db.execute('select key,data from {} where key = {}'.format(self._table,key))
return dict(cursor.fetchone())
def update(self, row):
self._db.execute('update {} set data={} where key = {}'.format(self._table,row['data'],row['key']))
self._conn.commit()
def delete(self, key):
self._db.execute('delete from {} where key = {}'.format(self._table,key))
self._conn.commit()
def __iter__(self):
self._db.execute('select * from {} '.format(self._table))
for row in self._db:
yield row
@property
def database(self):
return self.database
@database.setter
def database(self, fn):
self._database = fn
self._conn = psycopg2.connect(database = fn, user = "postgres", password = "moazam@123", host = "127.0.0.1", port = "5432")
self._db =self._conn.cursor()
print('#'*3 + " connected to database " +fn+' '+'#'*3)
@database.deleter
def database(self):
self.close()
@property
def table(self):
return self._table
@table.setter
def table(self, t):
self._table = t
def close(self):
self._db.close()
if __name__ == '__main__':
d=database(database='sample_db',table='test')
d.insert({"key": 1,"data": 10})
for i in d:
print(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment