Skip to content

Instantly share code, notes, and snippets.

@algonacci
Created February 28, 2024 05:39
Show Gist options
  • Save algonacci/1bacf372c3f15f3412d9957ec63d23b2 to your computer and use it in GitHub Desktop.
Save algonacci/1bacf372c3f15f3412d9957ec63d23b2 to your computer and use it in GitHub Desktop.
Check PostgreSQL Database Connection
import psycopg2
def check_tables_in_database(host, port, username, password, database):
try:
# Attempt to connect to the PostgreSQL database
connection = psycopg2.connect(
host=host,
port=port,
user=username,
password=password,
database=database
)
if connection:
print(f"Connected to the PostgreSQL database: {database}")
# Create a cursor to execute SQL queries
cursor = connection.cursor()
# Retrieve the list of tables in the database
cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")
# Fetch and print the table names
tables = cursor.fetchall()
if tables:
print("Tables in the database:")
for table in tables:
print(table[0])
# Close the cursor and connection
cursor.close()
connection.close()
except psycopg2.Error as e:
# If there's an error, print an error message
print(f"Error connecting to the database: {str(e)}")
if __name__ == "__main__":
# Replace with your PostgreSQL database connection details
host = '' # PostgreSQL server host
port = '' # PostgreSQL server port
username = '' # PostgreSQL username
password = '' # PostgreSQL password
database = '' # PostgreSQL database name
check_tables_in_database(host, port, username, password, database)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment