Connecting to PostgreSQL via Python

The following example shows how to connect to the PostgreSQL server via python.

Install psycopg2

pip install psycopg2

Connect to your database

import psycopg2

class PostgresqlConnection(object):
    def __init__(self): = 'your host'
        self.port = 'your port'
        self.user = 'your user name'
        self.passwd = 'your user password'
        self.db = 'your connect database name'

    def connect_postgresql(self):
        conn = psycopg2.connect(database=self.db, user=self.user, password=self.passwd,, port=self.port)
        return conn

    def operate_database(self):
        # examole select all database name
        connect = self.connect_postgresql()
        cursor = connect.cursor()
        sql = "SELECT datname FROM pg_database;"
        database_list = [i[0] for i in cursor.fetchall()]

if _name_ == '__main__':
Copyright © 2021 Cloud Clusters Inc. all right reserved,powered by GitbookRevised on 09/30/2021

results matching ""

    No results matching ""