Advertisement
Guest User

Untitled

a guest
Sep 8th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. #!/usr/bin/python
  2. import psycopg2
  3. import sys
  4.  
  5. def main():
  6.     #start of script
  7.     #Define our connection string
  8.     conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
  9.     # print the connection string we will use to connect
  10.     print "Connecting to database\n ->%s" % (conn_string)
  11.     try:
  12.         # get a connection, if a connect cannot be made an exception will be raised here
  13.         conn = psycopg2.connect(conn_string)
  14.         # conn.cursor will return a cursor oject, you can use this cursor to perform queries
  15.         cursor = conn.cursor()
  16.         print "Connected!\n"
  17.     except:
  18.         # Get the most recent exception
  19.         exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
  20.         # Exit the script and print an error telling what happened.
  21.         sys.exit("Database connection failed!\n ->%s" % (exceptionValue))
  22.  
  23.  
  24. if __name__ == "__main__":
  25.     sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement