0

I have a text file that has about 100 DB table names in it separated by a new line, and I have a function to return those table names in a list here:

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

I now want to connect to the DB and do a select count(*) on all those tables and store the table name and counts in some python object (list, dictionary, whatever). What I have so far is this:

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)

This is not working though, as it is appending the connection details to z. Clearly incorrect. Any ideas?

1 Answer 1

1

The problem isn't really about looping through multiple SQL statements at all. The question is how to get the result from a call to execute.

The answer to that is to call fetchone() on the cursor. This will give you a tuple, so get the first element of that:

a.execute('SELECT count(*) FROM {}'.format(table))
z.append(a.fetchone()[0])
Sign up to request clarification or add additional context in comments.

3 Comments

thank you Daniel. that worked great. Silly question, how would I then add the table name next to the result? The above returns the results which is great, but I want to associate it with the table as well
You could append a tuple of (table, a.fetchone..) fur example. Or make z a dict where the key is the table name.
thanks, i was just going to reply that I had figured it out using list comprehension. Thanks again

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.