From fccdad9bc01cc883b3460cdadb78fa1f3dba20c2 Mon Sep 17 00:00:00 2001 From: Matthew Huntington Date: Sun, 22 Oct 2023 20:07:19 -0400 Subject: [PATCH] export to csv --- python_sql/lessons/python_sql.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/python_sql/lessons/python_sql.md b/python_sql/lessons/python_sql.md index 8e8b085..cc543f2 100644 --- a/python_sql/lessons/python_sql.md +++ b/python_sql/lessons/python_sql.md @@ -141,7 +141,7 @@ sqlite3 mydb.db ## Migrating data to a SQLite ```python -#PostgreSQL +# PostgreSQL import psycopg2 conn = psycopg2.connect( @@ -202,3 +202,28 @@ with open('writedb.csv', 'w') as csvfile: ## Exporting data to CSV +```python +# PostgreSQL + +import psycopg2 +conn = psycopg2.connect( + database="my_db" +) +cursor = conn.cursor() + +cursor.execute("SELECT * FROM people") + +people = cursor.fetchall() + +cursor.close() +conn.close() + +# CSV + +import csv + +with open('writedb.csv', 'w') as csvfile: + writer = csv.writer(csvfile) + for person in people: + writer.writerow(person) +```