Guest User

Bard coding

a guest
Dec 6th, 2023
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. import psycopg2
  2. import csv
  3.  
  4. # Connect to the PostgreSQL database
  5. conn = psycopg2.connect(
  6.     host="localhost",
  7.     database="mydatabase",
  8.     user="postgres",
  9.     password="password"
  10. )
  11.  
  12. # Create a cursor to execute SQL queries
  13. cursor = conn.cursor()
  14.  
  15. # Execute a SQL query to retrieve data from a table
  16. sql_query = "SELECT * FROM mytable"
  17. cursor.execute(sql_query)
  18.  
  19. # Create a CSV writer object
  20. csv_writer = csv.writer(open("mytable.csv", "w"))
  21.  
  22. # Write the header row
  23. header = tuple(cursor.description)
  24. csv_writer.writerow(header)
  25.  
  26. # Write the data rows
  27. data_rows = cursor.fetchall()
  28. for row in data_rows:
  29.     csv_writer.writerow(row)
  30.  
  31. # Close the cursor and connection
  32. cursor.close()
  33. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment