Guest User

Untitled

a guest
Jan 14th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. import psycopg2
  2. import sys
  3.  
  4. class pgDatabase:
  5.  
  6. dbname = '***'
  7. user = '***'
  8. host = '***'
  9. password = '***'
  10.  
  11. def __init__(self):
  12. try:
  13. self.conn = psycopg2.connect("dbname='eomf' user='***' host='***' password='***'")
  14. except:
  15. print "Unnable to connect to database"
  16. sys.exit()
  17.  
  18. self.cur = self.conn.cursor()
  19.  
  20. def exists(self, f):
  21. query = "select count(*) from inventory_file where name = '%s'" % (f.filename)
  22. try:
  23. self.cur.execute(query)
  24. rows = self.cur.fetchall()
  25. return rows[0][0] > 0
  26. except:
  27. print "Error with query:" + query
  28.  
  29. def add(self, f):
  30. select = "SELECT count(*) from inventory_file WHERE tile_id = '%s' AND year = %s\
  31. AND day = %s AND dataset_id = '%s'" % (f.info('tile'), f.info('year'),
  32. f.info('day'), f.info('dataset').lower())
  33.  
  34. update = "UPDATE inventory_file SET name = '%s', timestamp = %s \
  35. WHERE tile_id = '%s' and year = %s and day = %s and dataset_id = '%s'" % \
  36. (f.filename, f.info('stamp'), f.info('tile'), f.info('year'),
  37. f.info('day'), f.info('dataset').lower())
  38.  
  39. insert = "INSERT INTO inventory_file (tile_id,name,year,day,timestamp,dataset_id) " + \
  40. "VALUES ('%s','%s',%s,%s,%s,'%s')" % \
  41. (f.info('tile'), f.filename, f.info('year'), \
  42. f.info('day'), f.info('stamp'), f.info('dataset').lower())
  43.  
  44. self.execute(select)
  45. rows = self.cur.fetchall()
  46. if rows[0][0] > 0:
  47. self.execute(update)
  48. else:
  49. self.execute(insert)
  50.  
  51. #Does not work, pseudo-sql
  52. def update(self, update, insert):
  53. query = "BEGIN; %s; if (!affected_rows){ %s; if (error) { ROLLBACK; %s ; } } COMMIT;" % (update, insert, update)
  54. self.execute(query)
  55.  
  56. def execute(self, query):
  57. try:
  58. #print query
  59. self.cur.execute(query)
  60. except:
  61. print "Error with query:" + query
  62. sys.exit()
  63.  
  64. self.conn.commit()
  65.  
  66. if __name__ == '__main__':
  67. #test
  68. db = pgDatabase()
Add Comment
Please, Sign In to add comment