簡體   English   中英

為什么Psycopg2在存儲過程中返回元組列表?

[英]Why does Psycopg2 return list of tuples in with Stored Procedure?

我一直在使用Psycopg2成功地從Postgres讀取存儲過程,並返回一個不錯的元組,這很容易處理。 例如...

    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

打印的行會給我('user@gmail.com','84894531656894hashedpassword5161651165',36,'test')

但是,當我運行以下代碼以使用存儲過程讀取一排固定裝置時,我會(看起來像)變得一團糟。

    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-08-28 21:00:00”,“ 2015-08-20 08:00:00”,“ 2015-08-25 17:00:00”,“團隊” ,,“團隊“ ,,“最終”)',)

我已經研究了游標類,無法理解為什么對於存儲過程它會像這樣輸出。 在Postgres中執行時,輸出位於完美的元組中。 使用Psycopg2會增加元組,但我不明白為什么?

我該如何更改它以獲得整潔的元組? 我對提出的要求能得到這個結果的要求不了解嗎?

我已經嘗試過callproc函數並獲得同樣無用的輸出。 任何對此的想法將是巨大的。

這是因為您正在直接SELECT函數的結果。 您的函數返回一組事物,每個“事物”恰好是一個元組,因此您將獲得一個返回的字符串化元組列表。 您想要的是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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