Advertisement
Guest User

Untitled

a guest
May 24th, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. from __future__ import print_function
  2.  
  3. from datetime import datetime
  4. from random import randint
  5. from time import sleep
  6. import psycopg2
  7.  
  8.  
  9. def main():
  10. try:
  11. connection = psycopg2.connect(user = "admin",
  12. password = "P@ssw0rd",
  13. host = "89.208.87.38",
  14. port = "5432",
  15. database = "myproddb")
  16.  
  17. cursor = connection.cursor()
  18. cursor.execute("SELECT version();")
  19. record = cursor.fetchone()
  20. print("Connection opened to", record[0])
  21.  
  22. cursor.execute(
  23. "INSERT INTO log VALUES ({});".format(randint(1, 10000)))
  24. connection.commit()
  25. cursor.execute("SELECT COUNT(event_id) from log;")
  26. record = cursor.fetchone()
  27. print("Logged a value, overall count: {}".format(record[0]))
  28. except Exception as error:
  29. print ("Error while connecting to PostgreSQL", error)
  30. finally:
  31. if connection:
  32. cursor.close()
  33. connection.close()
  34. print("Connection closed")
  35.  
  36.  
  37. if __name__ == '__main__':
  38. try:
  39. while True:
  40. try:
  41. print(datetime.now())
  42. main()
  43. sleep(3)
  44. except Exception as e:
  45. print("Caught error:\n", e)
  46. sleep(1)
  47. except KeyboardInterrupt:
  48. print("exit")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement