Guest User

Untitled

a guest
May 30th, 2018
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. import psycopg2.extras
  2. import os
  3.  
  4. def connect_db(autocommit=False):
  5. """ Connects to a data base and returns a connection and a cursor. """
  6. conn = psycopg2.connect(
  7. database=os.environ.get('DATABASE_DBNAME'),
  8. user=os.environ.get('DATABASE_USERNAME'),
  9. host=os.environ.get('DATABASE_HOST'),
  10. password=os.environ.get('DATABASE_PASSWORD')
  11. )
  12. conn.autocommit = autocommit
  13. cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  14. return {'conn': conn, 'cursor': cursor}
  15.  
  16.  
  17.  
  18. def execute_query(a_query, autocommit=True):
  19. """ Executes a query, printing out rows returned if any, returning the results, the connection and the cursor. """
  20. db = connect_db(autocommit=autocommit)
  21. conn, cursor = db.get('conn'), db.get('cursor')
  22. cursor.execute(a_query)
  23. result = cursor.fetchall()
  24. if result:
  25. print(len(result), "records fetched")
  26. return {'result':result, 'conn':conn, 'cursor':cursor}
  27.  
  28.  
  29. if if __name__ == '__main__':
  30. q = """ Select * from table limit 1 """
  31. res = execute_query(q)
  32. print(res)
Add Comment
Please, Sign In to add comment