简体   繁体   中英

Read sql queries in python

I am a little lost in something I am trying to do. Learning how to run sql within Python.

I have a db in in Python sqlite with three tables 1, 2, 3.

I then have a series of several queries I have written in a .sql file.

I have a loop created, but I am missing a step to read and execute the sql file.

# For each of the 3 tables, query the database and print the contents
for table in ['1', '2', '3']:

# Plug in the name of the table into SELECT * query
result = c.execute("SELECT * FROM %s;" % table);

# Get all rows.
rows = result.fetchall();

# \n represents an end-of-line
print "\n--- TABLE ", table, "\n"

My sql queries are written in a separate .sql file called queries.sql. Where do I put it in the loop?

Do post your sql queries to help you better. But looping is easily done this this -

#before the loop create mysql client & 
#create cursor to mysql server

for sql_query_template in open(sql_queries_file,'r'):
    result = c.execute(sql_query_template % table);
    rows   = result.fetchall();
    print 'Rows Fetched: %d' % len(rows)

I hope you get the idea...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM