Postgres CRUD operations with Python Part 2: [Insert]

Patrick Gichini
MindNinja
Published in
1 min readMar 26, 2019

Howdy fellow ninjas!

I trust the previous part of the series turned out well for you.

The main reason for having a table is to be able to store data so we’ll do an insert and test out our table.

Open your text editor and create a new file, am calling mine pg_insert.

By now, you already know the gist, we import our very dear psycopg2 library and define a connection.

After that, we define our insert query and proceed to execute it.

In my insert query, I am inserting a row that contains information about a cake type. Do you remember that my table had three columns? But in my insert query, I have specified only two columns. Why?

The column cake_id is a serial data type and serial data types are auto-generated. That means that I can leave it out of my insert query and it will be auto-incremented.

Our final code will look like:

By now, you might have noticed how useful putting our code inside the try, except, finally is by giving us feedback if something bad happens during execution. We can also do other things except printing feedback but for now, let’s stick to just the feedback.

If everything works out, you should get a nice beautiful row in your table. Try the script like 5 times with new rows.

NB: All code is available on this Github repo.

--

--

Patrick Gichini
MindNinja

Linux Ninja | Data Enthusiast | Sentimental Poet | Agent Boyfriend