[英]Tuple to List - Python / PostgreSQL return type of SETOF Record
所以从这段代码:
from dosql import *
import cgi
import simplejson as json
def index(req, userID):
userID = cgi.escape(userID)
get = doSql()
rec = get.execqry("select get_progressrecord('" + userID + "');", False)
return json.dumps(rec)
请注意,变量rec从我在PostgreSQL中创建的此已定义函数接收来自数据库的查询:
create or replace function
get_progressrecord(in int, out decimal(5,2), out decimal(5,2), out decimal(4,2), out text, out int, out decimal(4,2))
returns setof record as
$$
select height, weight, bmi, healthStatus, age, changePercentage from progressrecord
where userID = $1;
$$
language 'sql';
现在,假设userID = 7,并且我的表在userID(7)处的值为:
但是,当我尝试获取该记录时,会收到以下消息:
[[ “(300.00,30.00,3.33,体重,21,0.00)”]]
然后,我从彻底的分析中发现,这是一个TUPLES列表 。 含义, [(300.00,30.00,3.33,underweight,21,0.00)]是LIST的元组[0], (300.00,30.00,3.33,underweight,21,0.00)是TUPLE的元素[0]。
问题是,非常(300.00,30.00,3.33,underweight,21,0.00)被识别为一个字符串或任何字符串,并且深入到TUPLE列表中。 还有其他方法可以提取每个元素(剪切字符串吗?)并将其放入适当的列表中?
像这样: [300.00,30.00,3.33,体重不足,21,0.00]
非常感谢。 :)
SELECT get_progressrecord(ID)
将返回record
类型的单列。
SELECT * FROM get_progressrecord(ID)
将返回多个列(匹配您的out
参数)。
顺便说一句,您的输出字段没有名称这一事实可能会使您的函数难以使用。 我发现更简单的RETURNS SETOF RECORD
语法是:
CREATE OR REPLACE FUNCTION get_progressrecord(int)
RETURNS TABLE(
height decimal(5,2),
weight decimal(5,2),
bmi decimal(4,2),
healthStatus text,
age int,
changePercentage decimal(4,2)
) AS
...
您可以将map
功能用于此目的:
演示:
>>> tuple_list=[(300.00,30.00,3.33,'underweight',21,0.00),(300.00,30.00,3.33,'underweight',21,0.00)]
>>> map(list,tuple_list)
[[300.0, 30.0, 3.33, 'underweight', 21, 0.0], [300.0, 30.0, 3.33, 'underweight', 21, 0.0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.