0

I had no problem with SELECTing data in python from postgres database using cursor/execute. Just changed the sql to INSERT a row but nothing is inserted to DB. Can anyone let me know what should be modified? A little confused because everything is the same except for the sql statement.

<!-- language: python -->
@app.route("/addcontact")
def addcontact():

    # this connection/cursor setting showed no problem so far
    conn = pg.connect(conn_str)
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    sql = f"INSERT INTO jna (sid, phone, email) VALUES ('123','123','123')"
    cur.execute(sql) 
    return redirect("/contacts")

2 Answers2

2

first look at your table setup and make sure your variables are named right in the right order, format and all that, if your not logging into the specific database on the sql server it won't know where the table is, you might need to send something like 'USE databasename' before you do your insert statement so your computer is in the right place in the server.

I might not be up to date with the language but is that 'f' supposed to be right before the quotes? if thats in ur code that'd probably throw an error unless it has a use im not aware of or its not relevant to the problem.

Troy
  • 21
  • 1
1

You have to commit your transaction by adding the line below after execute(sql)

conn.commit()

Ref: Using INSERT with a PostgreSQL Database using Python

Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82