[英]Python connections to PostgreSQL using psycopg2 - Why need to close & re-open connection for ensuing code to work?
我在使用psycopg2時遇到了一個謎:
下面是程序代碼:
import psycopg2 # PostgreSQL module - need to install. See https://www.psycopg.org/docs/
lcConnectionString = "...obfuscated..."
loConnection = psycopg2.connect(lcConnectionString)
print(f"loConnection after '.connect()' is: {loConnection}")
loCursor = loConnection.cursor()
print(f"loCursor is {loCursor}")
try:
loCursor.execute("drop table TmpJobs")
print("Dropped TmpJobs table")
except Exception as exc:
print("Did not need to drop TmpJobs table table")
try:
loCursor.execute("drop table TmpSubset")
print("Dropped TmpSubset table")
except Exception as exc:
print("Did not need to drop TmpSubset table")
print(f"loConnection after 'exceptions' is: {loConnection}")
print(f"loCursor after 'exceptions' is {loCursor}")
# The rest of the program runs fine if close and reopen the connection. But crashes if don't.
llCloseAndReopen = False # Testing: True / False
if llCloseAndReopen:
loConnection.close()
print(f"loConnection after '.close()' is: {loConnection}")
loConnection = loCursor = None
loConnection = psycopg2.connect(lcConnectionString)
print(f"loConnection after 're-connect' is: {loConnection}")
print("\n-----------------------------------------\nSelecting from Jobs into subset result...")
loCursor2 = loConnection.cursor()
print(f"loCursor2 (just created): {loCursor2}")
loCursor2.execute(f"create temporary table TmpSubset as select * from Jobs where RowID % 100 = 0")
loCursor2.execute(f"select * from TmpSubset")
loResult = loCursor2.fetchall()
print(f"{len(loCursor2.description)} columns in Subset result")
lnRowCount = 0
for Row in loResult:
lnRowCount += 1
print(f"{lnRowCount}: {Row[0]}, {Row[1]}, {Row[2]}, {Row[3]}")
print(f"{lnRowCount} rows in Subset result")
如果連接沒有關閉並重新打開,則該行拋出異常:
loCursor2.execute(f"create temporary table TmpSubset as select * from Jobs where RowID % 100 = 0")
根據要求於 11 月 19 日添加:這是 Visual Studio 2019“輸出”窗口的最后一部分,顯示了最后的打印語句、異常消息和堆棧跟蹤:
Did not need to drop TmpSubset table
loConnection after 'exceptions' is: <connection object at 0x0579D878; dsn: 'user= ...obfuscated... host=localhost', closed: 0>
loCursor after 'exceptions' is <cursor object at 0x04815028; closed: 0>
-----------------------------------------
Selecting from Jobs into subset result...
loCursor2 (just created): <cursor object at 0x047B2F28; closed: 0>
current transaction is aborted, commands ignored until end of transaction block
Stack trace:
> File "J:\Python\Applications\SpeedTest\TestPostgreSQLPurePython2.py", line 49, in <module>
> loCursor2.execute(f"create temporary table TmpSubset as select * from Jobs where RowID % 100 = 0")
為什么 Python / psycopg2 無法在原始連接上使用新游標 (loCursor2),在“例外”觸發后? 有任何想法嗎?
您應該閱讀您收到的錯誤消息:
sycopg2.errors.InFailedSqlTransaction:當前事務被中止,命令被忽略,直到事務塊結束
一旦出現錯誤,您需要在繼續之前結束事務(回滾),因此將其添加到您的異常塊中。
loConnection.rollback()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.