Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import psycopg2
- import csv
- # Connect to the PostgreSQL database
- conn = psycopg2.connect(
- host="localhost",
- database="mydatabase",
- user="postgres",
- password="password"
- )
- # Create a cursor to execute SQL queries
- cursor = conn.cursor()
- # Execute a SQL query to retrieve data from a table
- sql_query = "SELECT * FROM mytable"
- cursor.execute(sql_query)
- # Create a CSV writer object
- csv_writer = csv.writer(open("mytable.csv", "w"))
- # Write the header row
- header = tuple(cursor.description)
- csv_writer.writerow(header)
- # Write the data rows
- data_rows = cursor.fetchall()
- for row in data_rows:
- csv_writer.writerow(row)
- # Close the cursor and connection
- cursor.close()
- conn.close()
Advertisement
Add Comment
Please, Sign In to add comment