假設我執行以下命令。檢測是否從psycopg2光標讀取?
insert into hello (username) values ('me')
,我跑起來像
cursor.fetchall()
我收到以下錯誤
psycopg2.ProgrammingError: no results to fetch
我如何可以檢測是否調用使用fetchall()或未經檢查的查詢是「插入」或「選擇」?
謝謝。
假設我執行以下命令。檢測是否從psycopg2光標讀取?
insert into hello (username) values ('me')
,我跑起來像
cursor.fetchall()
我收到以下錯誤
psycopg2.ProgrammingError: no results to fetch
我如何可以檢測是否調用使用fetchall()或未經檢查的查詢是「插入」或「選擇」?
謝謝。
看這個屬性:
cur.description
是否已執行查詢後,它將被設置爲無,如果沒有返回任何行,或否則將包含數據 - 例如:
(Column(name='id', type_code=20, display_size=None, internal_size=8, precision=None, scale=None, null_ok=None),)
捕捉異常並不理想,因爲可能有一種情況是您重寫了真正的異常。
所以你出現要問的是:
有什麼辦法,給出一個PostgreSQL光標,以從遊標中讀取數據,如果有任何?
我個人的偏好只是試圖運行fetchall()
然後捕獲不可避免的例外。
try:
data = cursor.fetchall()
do_something_with(data)
except psycopg2.ProgrammingError:
# take some other action
我決定也使用這種方法。多謝兄弟 – moeseth
第一行看起來像'cursor.execute(「insert into hello(username)values('me')」)'? – Compadre