You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

47 lines
1.4 KiB

import psycopg2
def execute_sql_file(file_path, connection):
with open(file_path, 'r') as file:
sql = file.read()
with connection.cursor() as cursor:
cursor.execute(sql)
connection.commit()
def main():
# Configurazione del database
db_config = {
"dbname": "postgres",
"user": "postgres",
"password": "example",
"host": "localhost",
"port": 5432
}
try:
# Connessione al database
connection = psycopg2.connect(**db_config)
print("Connessione al database riuscita.")
# Drop del database se esiste
connection.autocommit = True
with connection.cursor() as cursor:
cursor.execute("DROP DATABASE IF EXISTS simple_mensa")
cursor.execute("CREATE DATABASE simple_mensa")
connection.close()
# Riconnessione al nuovo database
db_config["dbname"] = "simple_mensa"
connection = psycopg2.connect(**db_config)
print("Database ricreato e riconnessione effettuata.")
# Esecuzione dello script SQL
execute_sql_file('schema.sql', connection)
print("Script SQL eseguito con successo.")
except Exception as e:
print(f"Errore durante la configurazione del database: {e}")
finally:
if connection:
connection.close()
print("Connessione al database chiusa.")
if __name__ == "__main__":
main()