Python sqlite循环认为数据库中的所有表

时间:2016-07-24 07:43:25

标签: python sqlite sqlalchemy

我在test.db文件中有700个表,并且想知道如果columnA值为-,我如何遍历所有这些表并返回表名?

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

如何将所有700个表放入all_tables

3 个答案:

答案 0 :(得分:2)

继续主题:

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()

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

注意:上面的代码未经测试,但可以让您了解如何处理此问题。

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