0

I have 700 tables in a test.db file, and was wondering how do I loop through all these tables and return the table name if columnA value is -?

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

How do I put all 700 tables in all_tables?

3 Answers 3

2

To continue on a theme:

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()
Sign up to request clarification or add additional context in comments.

Comments

1

SQLite

get all tables name:

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

Cycle

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

or one SQL request UNION

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

Comments

1

You could query the sqlite_master to get all the table names within your database: SELECT name FROM sqlite_master WHERE type = 'table'

sqlite_master can be thought of as a table that contains information about your databases (metadata).

A quick but most likely inefficient way (because it will be running 700 queries with 700 separate resultsets) to get the list of table names, loop through those tables and return data where 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

Note: Above code is untested but gives you an idea on how to approach this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.