RuntimeError: Can't begin a new transaction
时间: 2024-05-15 18:17:00 浏览: 79
This error typically occurs when you try to start a new transaction before committing or rolling back the previous one.
To resolve this error, you need to make sure that you properly close the previous transaction by either committing or rolling it back. You can also try to set the autocommit mode to True to avoid keeping the transaction open.
Here's an example of how to use autocommit mode in Python:
```
import psycopg2
# Connect to the database
conn = psycopg2.connect(database="mydb", user="myuser", password="mypassword", host="localhost", port="5432")
# Set autocommit mode to True
conn.autocommit = True
# Start a new transaction
cur = conn.cursor()
cur.execute("INSERT INTO mytable (col1, col2) VALUES (%s, %s)", (value1, value2))
# Close the cursor and connection
cur.close()
conn.close()
```
By setting the autocommit mode to True, the transaction will automatically commit after each SQL statement, so you won't have to worry about closing it manually.
阅读全文