2016-01-21 27 views
0

我一直在使用Psycopg2從Postgres中成功讀取存儲過程並獲得一個很好的元組返回,這很容易處理。例如...爲什麼Psycopg2使用存儲過程返回元組列表?

def authenticate(user, password): 
     conn = psycopg2.connect("dbname=MyDB host=localhost port=5433 user=postgres password=mypwd") 
     cur = conn.cursor() 
     retrieved_pwd = None 
     retrieved_userid = None 
     retrieved_user = None 
     retrieved_teamname = None 
     cur.execute(""" 
        select "email", "password", "userid", "teamname" 
        from "RegisteredUsers" 
        where "email" = '%s' 
        """ % user) 
     for row in cur: 
      print row 

,打印會給我行('[email protected] ' '84894531656894hashedpassword5161651165',36' 測試「)

然而,當我運行下面的代碼用一個存儲過程讀取一排燈具,我得到(看起來像我)一個邪惡的混亂。

def get_from_sql(userid): 
     conn = psycopg2.connect("dbname=MyDB host=localhost port=5433 user=postgres password=pwd") 
     fixture_cursor = conn.cursor() 
     callproc_params = [userid] 
     fixture_cursor.execute("select sppresentedfixtures(%s)", callproc_params) 
    for row in fixture_cursor: 
     print row 

所得輸出:

('(5 「2015年8月28日21時○○分00秒」, 「2015年8月20日8點00分零零秒」,「2015-08 -25 17:00:00「,」Team「,」Team「,」Final「)',)

我研究了遊標類,無法理解它爲什麼輸出這樣的存儲過程。在Postgres中執行時,輸出是一個完美的元組。使用Psycopg2添加到元組,我不明白爲什麼?

我該如何改變這個,讓我得到一個整齊的元組?我對於我提出的這個要求有什麼要求?

我已經嘗試過callproc函數,並得到一個同樣無益的輸出。任何想法都會很棒。

+1

你必須發佈pl/pgsql函數。對於我們所知道的,你的pl/pgsql函數可以將行轉換爲一個字符串。 – univerio

+0

CREATE OR REPLACE FUNCTION sppresentedfixtures(useridentity integer) RETURNS SETOF記錄AS $ BODY $ 選擇「Fixtures」。「Fixture_No」,「Fixtures」。「Fixture_Date」,「Fixtures」。「Opening_Date」,「Fixtures」。 「Home_Side_Score」,「Fixtures」,「Away_Side」,「Predictions」,「Away_Side_Score」,「Fixtures」,「Fixture_Stage」 from「Fixtures」 left join 「預測」 上的 「預測」, 「Fixture_No」= 「燈具」 「Fixture_No」 和 「預測」, 「用戶ID」=的UserIdentity $ BODY $ 語言SQL VOLATILE COST 100個 ROWS 1000。; ALTER FUNCTION sppresentedfixtures(整數) OWNER TO postgres; – LemusThelroy

回答

1

這是因爲你直接爲函數的結果。你的函數返回一組東西,而每個「東西」恰好是一個元組,所以你得到了一個字符串化的元組清單。你想要的是這樣的:

SELECT * FROM sppresentedfixtures(...) 

但這不起作用,因爲你會得到錯誤:

ERROR: a column definition list is required for functions returning "record" 

解決的辦法是返回,而不是一個表:

CREATE OR REPLACE FUNCTION sppresentedfixtures(useridentity integer) RETURNS TABLE(
    Fixture_No int, 
    Fixture_Date timestamp, 
    ... 
) AS 
$BODY$ 
    select 
    "Fixtures"."Fixture_No", 
    "Fixtures"."Fixture_Date", 
    ... 
    from "Fixtures" ... 
$BODY$ LANGUAGE sql 
+0

謝謝,這真的很有幫助,我會試一試! 只是爲了幫助我理解,爲什麼在Postgres中,當我運行查詢「select sppresentedfixtures(30)」時,我得到一個乾淨的元組。但是使用psycopg2給了我一個不同的結果?在一天結束時,它不僅僅是相同的存儲過程? – LemusThelroy

+1

@LemusThelroy我的猜測是psql有能力處理'record'類型,而psycopg2不能。 – univerio

+0

你的建議奏效了,我想我理解你的解釋爲什麼它不起作用,所以再次感謝你 – LemusThelroy