问题
From https://wiki.postgresql.org/wiki/Psycopg2_Tutorial
PostgreSQL does not have an autocommit facility which means that all queries will execute within a transaction.
Execution within a transaction is a very good thing, it ensures data integrity and allows for appropriate error handling. However there are queries that can not be run from within a transaction. Take the following example.
#/usr/bin/python2.4 # # import psycopg2 # Try to connect try: conn=psycopg2.connect("dbname='template1' user='dbuser' password='mypass'") except: print "I am unable to connect to the database." cur = conn.cursor() try: cur.execute("""DROP DATABASE foo_test""") except: print "I can't drop our test database!"
This code would actually fail with the printed message of "I can't drop our test database!" PostgreSQL can not drop databases within a transaction, it is an all or nothing command. If you want to drop the database you would need to change the isolation level of the database this is done using the following.
conn.set_isolation_level(0)
You would place the above immediately preceding the DROP DATABASE cursor execution.
I was wondering why
"PostgreSQL does not have an autocommit facility which means that all queries will execute within a transaction."
"PostgreSQL can not drop databases within a transaction"
"If you want to drop the database you would need to change the isolation level of the database"
Thanks.
Update: What does autocommit mean in postgresql and psycopg2? answer my question
回答1:
All the 3 are related to Python and its DB connector library, not the PostgreSQL itself:
- PostgreSQL has an
autocommit
and it is active by default - which means that every SQL statement is immediately executed. When you start a transaction block, this autocommit mode is disabled until you finish the transaction (either by COMMIT or ROLLBACK) - The operation of destroying a database is implemented in a way where you can not run it from inside a transaction block. Also keep in mind that unlike most other databases PostgreSQL allows almost all DDL statements (obviously not the DROP DATABASE one) to be executed inside a transaction.
- Actually you can not drop a database if anyone (including you) is currently connected to this database - so it does not matter what is your isolation level, you still have to connect to another database (e.g.
postgres
)
来源:https://stackoverflow.com/questions/51858497/why-does-having-no-autocommit-facility-mean-that-all-queries-execute-within-a-tr