From 329466cfde3ae0d5e4947c9c82d67491b2acf8bf Mon Sep 17 00:00:00 2001 From: Matthew Huntington Date: Sun, 22 Oct 2023 15:25:52 -0400 Subject: [PATCH] running queries with python --- python_sql/labs/README.md | 4 ++++ python_sql/lessons/connect.md | 42 ++++++++++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 python_sql/labs/README.md diff --git a/python_sql/labs/README.md b/python_sql/labs/README.md new file mode 100644 index 0000000..22e62c1 --- /dev/null +++ b/python_sql/labs/README.md @@ -0,0 +1,4 @@ +# Labs + +1. create a terminal based customer relationship management tool +1. migrate the CRM from previous lab to simple web app with an API diff --git a/python_sql/lessons/connect.md b/python_sql/lessons/connect.md index 64fe7a5..7fe7ec7 100644 --- a/python_sql/lessons/connect.md +++ b/python_sql/lessons/connect.md @@ -1,4 +1,4 @@ -# Plan for Python + SQL +# Python + SQL ## Lessons @@ -29,19 +29,51 @@ python -m pip install psycopg2-binary ```python import psycopg2 conn = psycopg2.connect( - database="supertest_lab" + database="my_db" ) + +# close connection +conn.close() ``` ## Running Queries with Python +Select many + ```python cursor = conn.cursor() + cursor.execute("SELECT * FROM people") print(cursor.fetchall()) + +# close connection +cursor.close() ``` -## Labs +Select one -1. create a terminal based customer relationship management tool -1. migrate the CRM from previous lab to simple web app with an API +```ptyon +cursor.execute("SELECT * FROM people WHERE id = 12") +print(cursor.fetchone()) +``` + +Insert + +```python +cursor.execute("INSERT INTO people (name, age) VALUES (%s, %s)", ['Matt', 43]) +conn.commit() +``` + +Delete + +```python +cursor.execute("DELETE FROM people WHERE id = 12"); +conn.commit() +``` + +Update + +```python +cursor.execute("UPDATE people SET name = %s, age = %s WHERE id = %s", ['Matt', 43, 20]) +conn.commit() +```