How to insert a Python tuple in a PostgreSql database?


PostgreSql database is by default installed on port number 5432. Python interface to PostgreSql is provided by installing psycopg2 module. Assuming that test database and employee table with fname, sname, age, gender and salary fields is available.

First establish connection and obtain cursor object by following statements in Python script.

import psycopg2
conn = psycopg2.connect(database = "test", user = "postgres", password = "pass123", host = "localhost", port = "5432")
cur = conn.cursor()

Data to be inserted in employee table is stored in the form of tuple object

t1=('Mac', 'Mohan', 20, 'M', 2000)

Next set up the insert query using this tuple

sql="insert into employee values(%s,%s,%d,%s,%d)" %t1

Now this query is executed using the cursor object

cursor.execute(sql)

Result of this statement will be that employee table will show new record added in it.

Updated on: 18-Feb-2020

891 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements