簡體   English   中英

遍歷多個SQL語句並將結果存儲在Python對象中

[英]Loop through multiple SQL statements and store the results in Python object

我有一個文本文件,其中包含大約100個DB表名,並用換行符隔開,並且我有一個函數可以在此處的列表中返回這些表名:

def grab_tables(self):
    table_list = []
    with open('tables.txt', 'r') as file:
        datalines = (line.rstrip('\r\n') for line in file)
        for line in datalines:
            table_list.append(line)
    return table_list

現在,我想連接到數據庫並在所有這些表上執行select count(*)並將表名和計數存儲在某些python對象(列表,字典等)中。 我到目前為止所擁有的是:

def run_sql(self):
    s = self.connection_src() #function that connects to Oracle DB
    tables = self.grab_tables()
    a = s.cursor()
    z = []
    for table in tables:            
        a.execute('SELECT count(*) FROM {}'.format(table))
        z.append(a)

    print(z)

但是,這不起作用,因為它將連接詳細信息附加到z。 顯然不正確。 有任何想法嗎?

問題根本不在於完全遍歷多個SQL語句。 問題是如何從execute調用獲得結果。

答案是在光標上調用fetchone() 這將為您提供一個元組,因此請獲取其中的第一個元素:

a.execute('SELECT count(*) FROM {}'.format(table))
z.append(a.fetchone()[0])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM