Untitled

mail@pastecode.io avatar
unknown
python
a year ago
1.0 kB
2
Indexable
Never
import psycopg2
import csv


db_params = {
    "dbname": "",
    "user": "",
    "password": "",
    "host": "",
    "port": ""
}

output_file = "postgresdb_data.csv"

try:
    connection = psycopg2.connect(**db_params)

    cursor = connection.cursor()

    query = "SELECT * FROM (table_name)"

    cursor.execute(query)

    rows = cursor.fetchall()

    with open(output_file, "w", newline="") as csvfile:
        csv_writer = csv.writer(csvfile)
        
        # Write the header (column names) to the CSV file
        column_names = [desc[0] for desc in cursor.description]
        csv_writer.writerow(column_names)
        
        # Write the data rows to the CSV file
        csv_writer.writerows(rows)

    print(f"Data saved to {output_file}")

except (Exception, psycopg2.Error) as error:
    print("Error connecting to the database:", error)

finally:
    if connection:
        cursor.close()
        connection.close()
        print("Database connection closed.")