2016-07-24 32 views
0

我在test.db文件中有700個表格,並且想知道如何循環所有這些表格並返回表格名稱,如果columnA值爲-python sqlite循環考慮數據庫中的所有表格

connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"') 

如何在all_tables中放置全部700個表格?

回答

1

你可以查詢sqlite_master到你的數據庫中獲得所有的表名:SELECT name FROM sqlite_master WHERE type = 'table'

sqlite_master可以被看作是包含數據庫(元數據)信息的表格。

快速但極有可能低效的方式(因爲它會運行700個查詢與700個不同的結果集)通過這些表來獲取表名的列表,循環和返回數據,其中columnA = "-"

for row in connection.execute('SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name').fetchall() 
    for result in connection.execute('SELECT * FROM ' + row[1] + ' WHERE "columnA" = "-"').fetchall() 
    # do something with results 

注:上面的代碼沒有經過測試,但給你一個關於如何解決這個問題的想法。

1

SQLite的

得到所有表名:

SELECT name FROM sqlite_master WHERE type='table' ORDER BY name; 

週期

for table in tables: 
    ... 
    connection.execute('SELECT * FROM "table1" WHERE "columnA" = "-"') 

或一個SQL UNION要求

sql = [] 
for table in tables 
    sql.append('(SELECT * FROM "' + table + '" WHERE "columnA" = "-";)') 
' UNION '.join(sql) 
1

要繼續圍繞着一個主題:

import sqlite3 
try: 
    conn = sqlite3.connect('/home/rolf/my.db') 
except sqlite3.Error as e: 
    print('Db Not found', str(e)) 
db_list = [] 
mycursor = conn.cursor() 
for db_name in mycursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'"): 
    db_list.append(db_name) 
for x in db_list: 
    print "Searching",x[0] 
    try: 
     mycursor.execute('SELECT * FROM '+x[0]+' WHERE columnA" = "-"') 
     stats = mycursor.fetchall() 
     for stat in stats: 
      print stat, "found in ", x 
    except sqlite3.Error as e: 
     continue 
conn.close() 
相關問題