簡體   English   中英

使用 psycopg2 與 PostgreSQL 的 Python 連接 - 為什么需要關閉並重新打開連接才能使代碼正常工作?

[英]Python connections to PostgreSQL using psycopg2 - Why need to close & re-open connection for ensuing code to work?

我在使用psycopg2時遇到了一個謎:

  • 我的程序連接正常,並創建一個游標 OK
  • 此游標在“try ... except”結構中用於刪除兩個臨時表(如果存在)
  • ('except' 邏輯對這兩個都運行,因為這些表不存在。)
  • 但是,接下來的程序的其余部分在第一個“.execute()”處崩潰,因為它無法使用它似乎從該連接創建的新游標。
  • 如果我關閉連接並重新打開它(或創建並使用第二個連接),隨后的邏輯運行良好。
  • (如果我注釋掉“try ...except”兩個構造,它運行良好,可以理解。)

下面是程序代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM