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):
        self.host = '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, host=self.host, port=self.port)
        conn.set_isolation_level(0)
        return conn

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


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

results matching ""

    No results matching ""