1

I am trying to insert a new row into postgresql database using psycopg2 and flask. Here is the code:

con = psycopg2.connect("host=localhost dbname=crm_whatsapp user=user_name password=user_password")
cur = con.cursor()
    create = cur.execute("INSERT INTO crm_user_chat_data (number) VALUES (%s) returning id",(user_number,)) //Here it returns none
con.commit()

But I am getting None instead of id.

How can i solve this?

davidism
  • 121,510
  • 29
  • 395
  • 339
KbiR
  • 4,047
  • 6
  • 37
  • 103
  • Does this answer your question? [How to retrieve inserted id after inserting row in SQLite using Python?](https://stackoverflow.com/questions/6242756/how-to-retrieve-inserted-id-after-inserting-row-in-sqlite-using-python) – Marcin Oct 31 '19 at 13:06
  • @Marcin, i tried `lastrowid`, but it returns `0` always. – KbiR Oct 31 '19 at 13:09
  • What about How do I get the “id” after INSERT into MySQL database with Python? https://stackoverflow.com/questions/2548493/ – Marcin Oct 31 '19 at 16:31

1 Answers1

0

You need to fetch() from the cursor to get the id:

cur = con.cursor()
create = cur.execute("INSERT INTO crm_user_chat_data (number) VALUES (%s) returning id",(user_number,))
con.commit()    
insertId = cur.fetchone()
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47