# Extra psycopg2 examples
### Reading data with `psycopg2`
Write a `SQL` statement using the `SELECT` keyword and execute it with the cursor.
```python=
# Selecting records
def get_widgets_by_color(color):
# Fetching many records (find widgets by color):
with psycopg2.connect(**CONNECTION_PARAMETERS) as conn:
with conn.cursor() as curs:
curs.execute(
"""
SELECT * FROM widgets
WHERE color = %(color)s
""",
{"color": color})
results = curs.fetchall()
return results
```
---
### Updating data with `psycopg2`
Use `UPDATE` keyword from `SQL`.
```python=
# Updating an existing record
def update_widget_color(widget_id, new_color):
with psycopg2.connect(**CONNECTION_PARAMETERS) as conn:
with conn.cursor() as curs:
curs.execute(
"""
UPDATE widgets SET color = %(new_color)s
WHERE id = %(widget_id)s
""",
{
"widget_id": widget_id,
"new_color": new_color})
```
---
### Deleting data with `psycopg2`
Use `DELETE` keyword from `SQL`. (... see a pattern here?).
```python=
def delete_widget(widget_id):
with psycopg2.connect(**CONNECTION_PARAMETERS) as conn:
with conn.cursor() as curs:
curs.execute(
"""
DELETE FROM widgets
WHERE id = %(widget_id)s
""",
{"widget_id": widget_id})
```
---