Python psycopg2 not inserting into postgresql table

前端 未结 4 1010
抹茶落季
抹茶落季 2020-12-09 01:14

I\'m using the following to try and insert a record into a postgresql database table, but it\'s not working. I don\'t get any errors, but there are no records in the table.

4条回答
  •  有刺的猬
    2020-12-09 02:11

    psycopg2 is Python DB API-compliant, so the auto-commit feature is off by default. You need to call conn.commit to commit any pending transaction to the database. As connections (and cursors) are context managers, you can simply use the with statement to automatically commit/rollback a transaction on leaving the context:

    with conn, conn.cursor() as cur:  # start a transaction and create a cursor
        cur.execute(sql)
    

    From the docs:

    When a connection exits the with block, if no exception has been raised by the block, the transaction is committed. In case of exception the transaction is rolled back.

    When a cursor exits the with block it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected.

提交回复
热议问题