2016-01-21 62 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