将SQL结果从函数返回为数组

时间:2012-10-15 17:02:34

标签: python

由于查询返回的结果超过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')]

2 个答案:

答案 0 :(得分:4)

直接的答案是改变:

for data_out in data:
    data_out result

为:

for data_out in data:
    yield data_out

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

答案 1 :(得分: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