Advertisement
Guest User

Untitled

a guest
Sep 28th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. def config(filename='database.ini', section='postgresql'):
  2. parser = ConfigParser()
  3. parser.read(filename)
  4.  
  5. db = {}
  6. if parser.has_section(section):
  7. params = parser.items(section)
  8. for param in params:
  9. db[param[0]] = param[1]
  10. else:
  11. raise Exception('Section {0} not found in the {1} file'.format(section, filename))
  12.  
  13. return db
  14.  
  15. import psycopg2
  16. import config import config
  17.  
  18. def connect():
  19. """ Connect to the PostgreSQL database server """
  20. conn = None
  21. try:
  22. # read connection parameters
  23. params = config()
  24.  
  25. # connect to the PostgreSQL server
  26. print('Connecting to the PostgreSQL database...')
  27. conn = psycopg2.connect(**params)
  28.  
  29. # create a cursor
  30. cur = conn.cursor()
  31.  
  32. # execute a statement
  33. print('PostgreSQL database version:')
  34. cur.execute('SELECT version()')
  35.  
  36. # display the PostgreSQL database server version
  37. db_version = cur.fetchone()
  38. print(db_version)
  39.  
  40. # close the communication with the PostgreSQL
  41. cur.close()
  42. except (Exception, psycopg2.DatabaseError) as error:
  43. print(error)
  44. finally:
  45. if conn is not None:
  46. conn.close()
  47. print('Database connection closed.')
  48.  
  49.  
  50. if __name__ == '__main__':
  51. connect()
  52.  
  53. [postgresql]
  54. host=localhost
  55. database= ***
  56. user=postgres
  57. password= ***
  58.  
  59. could not connect to server: Connection refused (0x0000274D/10061)
  60. Is the server running on host "localhost" (::1) and accepting
  61. TCP/IP connections on port 5432?
  62. could not connect to server: Connection refused (0x0000274D/10061)
  63. Is the server running on host "localhost" (127.0.0.1) and accepting
  64. TCP/IP connections on port 5432?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement