PostgreSQL psycopg2 返回一个字符串元组而不是元组元组? [英] PostgreSQL psycopg2 returns a tuple of strings instead of tuple of tuples?

查看:56
本文介绍了PostgreSQL psycopg2 返回一个字符串元组而不是元组元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,在搜索 Google/SO 后我不太确定如何解决它.

I have a weird problem, and I'm not too sure how to fix it after searching Google/SO found nothing similar.

当我试图从游标中获取查询结果时,它给了我一个元组元组,除了元组是字符串?下面是代码.

When I tried to grab query results from the cursor, it gives me a tuple of tuples, except the tuples are strings? Below is the code.

def queryFeeds(db):
   sql = """SELECT ngo.n_id, feeds.url FROM ngo 
    JOIN feeds ON ngo.n_id = feeds.n_id;"""

   db.c.execute(sql)

   feeds = db.c.fetchall()

   return feeds

这里的打印输出是函数返回的 feeds 变量:

The print output is here for the feeds variable returned by the function:

feeds[0]
('(277,http://resultsuk.wordpress.com/feed)',)

feeds[0][0]
'(277,http://resultsuk.wordpress.com/feed)'

type(feeds[0][0])
<type 'str'>

feeds[0][0][0:10]
'(277,http:'

db 只是一个有数据库连接的类,其中 db.c 是游标.提前致谢.删除的数据是 http://链接,因为我的声誉低,所以不会让我发布.

The db is just a class that has the database connection, where db.c is the cursor. Thanks in advance. The deleted data are http: // links that SO won't let me post because of my low reputation.

干杯,

卢卡斯

推荐答案

SELECT 子句中的字段中删除括号.

Remove the parentheses from the fields in the SELECT clause.

我遇到了同样的问题(尽管使用 RETURNING 子句而不是 SELECT),@user2524674 的评论应该是一个答案.在编辑问题之前,SELECT 子句中的字段用括号括起来,即

I had this same issue (though with a RETURNING clause instead of a SELECT), and the comment by @user2524674 deserves to be an answer. Before the question was edited, the fields in the SELECT clause were surrounded by parentheses, i.e.

SELECT (ngo.n_id, feeds.url)

并且返回的结果是一个字符串而不是一个实际的元组.将此更改为

and the result returned is a string rather than an actual tuple. Changing this to

SELECT ngo.n_id, feeds.url

导致 psycopg2 返回一个实际的值元组.

causes psycopg2 to return an actual tuple of values.

这篇关于PostgreSQL psycopg2 返回一个字符串元组而不是元组元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆