2

由于查询返回超过 1 个结果,在 Get_results 类中,我如何将 data_out 作为数组返回以迭代查询结果?

import psycopg2
import sys

class Get_results():
    def db_call(self,query,dbHost,dbName,dbUser,dbPass):
        try:
            con = None
            con = psycopg2.connect(host=dbHost, database=dbName,
                                   user=dbUser, password=dbPass)
            cur = con.cursor()
            cur.execute(query)
            data = cur.fetchall()
            for data_out in data:
                return data_out
        except psycopg2.DatabaseError, e:
                print 'Error %s' % e
                sys.exit(1)
        finally:
            if con:
                con.close()

 sql = " some sql "
 w = Get_results()
 for i in  w.db_call(sql, dbHost, dbName, dbUser, dbPass):
     print "The result is : " + i

对于附加信息,如果我在得到结果print data后 立即添加data = cur.fetchall()

[('The_Galaxy', 'The_Galaxy:star'),
 ('The_Galaxy', 'The_Galaxy:planet')]
4

2 回答 2

4

直接的答案是改变:

for data_out in data:
    data_out result

到:

for data_out in data:
    yield data_out

但是您应该考虑使用with语句(如果 DB API 支持它),并简化代码 - 这可以通过创建生成器函数来完成(一个类是 OTT)

于 2012-10-15T17:15:04.970 回答
3
import psycopg2
import sys

class Get_results():
    def db_call(self,query,dbHost,dbName,dbUser,dbPass):
        try:
            con = None
            con = psycopg2.connect(host=dbHost, database=dbName,
                                   user=dbUser, password=dbPass)
            cur = con.cursor()
            cur.execute(query)
            data = cur.fetchall()  
            resultList = []  
            for data_out in data:  
                resultList.append(data_out[1])  


            return resultList   
        except psycopg2.DatabaseError, e:
                print 'Error %s' % e
                sys.exit(1)
        finally:
            if con:
                con.close()

 sql = " some sql "
 w = Get_results()
 for i in  w.db_call(sql, dbHost, dbName, dbUser, dbPass):
     print "The result is : " + i
于 2012-10-15T17:19:38.313 回答