Skip to content

Instantly share code, notes, and snippets.

@beugley
Last active August 26, 2019 14:23
Show Gist options
  • Save beugley/cf5f87447e4a1499007bf0bff9a3fd8a to your computer and use it in GitHub Desktop.
Save beugley/cf5f87447e4a1499007bf0bff9a3fd8a to your computer and use it in GitHub Desktop.
Python script to connect to postgresql database
def connect(self):
''' Open a connection to the database '''
logging.info("Connecting to database '%s'" % config['DB_DBNAME'])
dirname = os.path.dirname(os.path.realpath(sys.argv[0]))
DB_PASSWORD_FILE = (dirname + "/.dbpass." + config['DB_HOST'] + "." +
config['DB_USER'])
with open(DB_PASSWORD_FILE) as pwd:
DB_PASSWORD = pwd.readline().strip()
self.conn = psycopg2.connect("host='%s' port='%s' dbname='%s' "
"user='%s' password='%s'" % (
config['DB_HOST'], config['DB_PORT'],
config['DB_DBNAME'], config['DB_USER'],
DB_PASSWORD))
self.cursor = self.conn.cursor()
self.cursor.execute('set search_path to %s' % config['DB_SCHEMA'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment