Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import psycopg2
- class MyDatabase(object):
- _INSERT_QUERY_TEMPLATE = "INSERT INTO mytable (name, surname) VALUES (%s, %s)"
- _SELECT_QUERY = "SELECT id, name, surname FROM mytable"
- _UPDATE_QUERY_TEMPLATE = "UPDATE mytable SET surname = %s WHERE name = %s)"
- _DELETE_QUERY_TEMPLATE = "DELETE FROM mytable WHERE name = %s"
- def __init__(self, user, password, dbname="postgres", host="127.0.0.1",
- port=5432):
- self._user = user
- self._password = password
- self._host = host
- self._port = port
- self._dbname = dbname
- self._connection = None
- def _GetConnection(self):
- return psycopg2.connect(dbname=self._dbname, user=self._user,
- password=self._password, host=self._host, port=self._port)
- # Better to be more specific, like: InsertUser, or InsertPerson. Depends on
- # the table you insert into.
- def InsertValues(name, surname):
- try:
- with self._GetConnection() as conn:
- cur = conn.cursor()
- query = cur.mogrify(_INSERT_TEMPLATE, (name, surname))
- cur.execute(query)
- except Exception, e:
- print "Failed to insert values:", name, surname
- print e
- def GetAllValues(self):
- try:
- with self._GetConnection() as conn:
- cur = conn.cursor()
- cur.execut(_SELECT_QUERY)
- return cur.fetchall()
- except Exception, e:
- print "Failed to get values.", e
- def UpdateSurnameByName(self, name, surname):
- try:
- with self._GetConnection() as conn:
- cur = conn.cursor()
- query = cur.mogrify(_UPDATE_QUERY_TEMPLATE, surname, name)
- cur.execute(query)
- except Exception, e:
- print "Failed to update values:", name, surname
- print e
- def DeleteValuesByName(self, name):
- try:
- with self._GetConnection() as conn:
- cur = conn.cursor()
- query = cur.mogrify(_DELETE_QUERY_TEMPLATE, name)
- cur.execute(query)
- except Exception, e:
- print "Failed to delete values with name =", name
- print e
- def printValues(values):
- for row in rows:
- print "id = ", values[0]
- print "name = ", values[1]
- print "surname = ", values[2]
- print "----------\n"
- def main():
- # TODO: read configuration with ini parser.
- user = "postgres"
- passwd = "success"
- db = MyDatabase(user=user, password=passwd)
- db.InsertValues(name='John', surname='McRead')
- printValues(fordb.GetAllValues())
- db.UpdateSurnameByName(name='John', surname='McDonald')
- printValues(fordb.GetAllValues())
- db.DeleteValuesByName('John')
- printValues(fordb.GetAllValues())
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement