Build: Insert Data into Postgres Using Python
Build: Insert Data into Postgres Using Python
Use psycopg2 to
add new records on your Raspberry Pi
Now that you’ve connected to your Postgres database and successfully queried existing data, it’s time to go the other direction—inserting new data using Python. This post will walk you through the script_two.py file included in the Gist, and show you how to insert a user into the demo_users table with a simple call.
You’re building out real CRUD capability now, and that means you’re no longer just testing—you’re actively shaping your database from code.
Now that you’ve connected to your Postgres database and successfully queried existing data, it’s time to go the other direction—inserting new data using Python. This post will walk you through the script_two.py file included in the Gist, and show you how to insert a user into the demo_users table with a simple call.
You’re building out real CRUD capability now, and that means you’re no longer just testing—you’re actively shaping your database from code.
Step 1: Review the
Insert Script
This
confirms your Python code has full insert capability. You’re now ready to
build more advanced tools, automation scripts, or RESTful APIs on top of
this.
Here’s the full script_two.py script from the Github Gist. It takes a username and email, inserts a new row
into the demo_users table, and commits the change:
Step 2: Run the Insert
You can run this from the command line like any other Python file:
If everything’s
working correctly, you’ll see:
Step 3: Confirm the Insert
This
is safe, parameterized SQL—no string interpolation or injection risk here.
You can run this from the command line like any other Python file:
Step 3: Confirm the Insert
To verify the new record is
actually in the database, run script_one.py again:
Now you should see
your original record and the new one you just inserted:
What’s Next: Beyond the Basics
This concludes
the core Raspberry Pi + Postgres mini-series. From here, you can:
Stay tuned. The tools are coming.
- Expand your table structure
- Add more scripts (for updating or deleting)
- Wrap this logic into a web service or CLI tool
Stay tuned. The tools are coming.
Need Postgres Expertise?
We're happy to help you with your Postgres projects! Feel free to contact us.
Email: info@pacificw.com
Image: Gemini
Comments
Post a Comment