import psycopg2
from psycopg2 import OperationalError
# Database connection config
db_config = {
'host': 'localhost',
'database': 'existing_database', # Replace with the actual database name
'user': 'your_username',
'password': 'your_password',
}
try:
# Attempt to connect to the database
connection = psycopg2.connect(**db_config)
print("Successfully connected to the database!")
# ... Your code to perform database operations ...
except OperationalError as error:
# Handle the "database does not exist" error
if 'database "existing_database" does not exist' in str(error):
# Database does not exist, create it using some desired logic
new_db_config = {
'host': 'localhost',
'database': 'existing_database', # Replace with the desired database name
'user': 'your_username',
'password': 'your_password',
}
connection = psycopg2.connect(**new_db_config)
print("Created a new database:", new_db_config['database'])
# ... Additional code to set up the newly created database ...
else:
print("Failed to connect to the database:", error)