Bear reading some booksBear reading some books

The following python script gets all databases from a PostgreSQL server.

import psycopg2

def get_databases(server_name, user, password, db_name='postgres'):
    try:
        conn = psycopg2.connect(
            host=server_name,
            user=user,
            password=password,
            dbname=db_name
        )
        cursor = conn.cursor()

        # Query to get the list of databases
        cursor.execute("SELECT datname FROM pg_database WHERE datistemplate = false;")
        databases = [db[0] for db in cursor.fetchall()]

        return databases

    except Exception as e:
        print(f"An error occurred: {e}")
        return []

    finally:
        cursor.close()
        conn.close()

# Example usage (uncomment and modify with your details for testing)
# print(get_databases('your_server_name', 'your_username', 'your_password'))

By Rudy