Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def config(filename='database.ini', section='postgresql'):
- parser = ConfigParser()
- parser.read(filename)
- db = {}
- if parser.has_section(section):
- params = parser.items(section)
- for param in params:
- db[param[0]] = param[1]
- else:
- raise Exception('Section {0} not found in the {1} file'.format(section, filename))
- return db
- import psycopg2
- import config import config
- def connect():
- """ Connect to the PostgreSQL database server """
- conn = None
- try:
- # read connection parameters
- params = config()
- # connect to the PostgreSQL server
- print('Connecting to the PostgreSQL database...')
- conn = psycopg2.connect(**params)
- # create a cursor
- cur = conn.cursor()
- # execute a statement
- print('PostgreSQL database version:')
- cur.execute('SELECT version()')
- # display the PostgreSQL database server version
- db_version = cur.fetchone()
- print(db_version)
- # close the communication with the PostgreSQL
- cur.close()
- except (Exception, psycopg2.DatabaseError) as error:
- print(error)
- finally:
- if conn is not None:
- conn.close()
- print('Database connection closed.')
- if __name__ == '__main__':
- connect()
- [postgresql]
- host=localhost
- database= ***
- user=postgres
- password= ***
- could not connect to server: Connection refused (0x0000274D/10061)
- Is the server running on host "localhost" (::1) and accepting
- TCP/IP connections on port 5432?
- could not connect to server: Connection refused (0x0000274D/10061)
- Is the server running on host "localhost" (127.0.0.1) and accepting
- TCP/IP connections on port 5432?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement