Inserting data into MySQL database from Python
Question: I have 2 tables TBL1 and TBL2. TBL1 has 3 columns date, id, nSql. TBL2 has 3
columns date, custId, userId. I have 17 rows in TBL1 with id 1 to 17 (which
will grow later). Each nSql has a SQL query in it. For example nSql for id=1
is: "select date, pId as custId, tId as userId from TBL3" For example nSql for
id=2 is: "select date, qId as custId, rId as userId from TBL4" ... nSql result
is always same 3 columns.

Below query only runs nSql for id =1. So, in TBL2 I have only output for nSql
=1. I want result for all nSql. I want my query to run for all nSql not just
for id =1.

    
    
    import MySQLdb
    
    # Open database connection
    
    con=MySQLdb.Connection(host="localhost", user="root", passwd="root", db="test")
    
    # create a cursor object using cursor() method
    
    cur=con.cursor()
    
    selectStatement=("select nSql from TBL1") # I do not want to limit the number of id to select. For example, I do not want: select nSql from TBL1 where id in (1, 2, ..17)
    cur.execute(selectStatement)
    res=cur.fetchone()
    nSql=res[0]
    cur.execute(nSql)
    reslt=cur.fetchall()
    for row in reslt:
        date= row[0]
        custId= row[1]
        userId=row[2]
        insertStatement=("insert into TBL2( date, custId, userId) values ('%s', %d, %d)" % (date, custId, userId))
        cur.execute(insertStatement)
        con.commit() 
    


Answer: You already fetch the `nSql` result and loop over it. You need to loop over
both:

    
    
    cur.execute(selectStatement)
    res = cur.fetchall()
    for outerrow in res:
        nSql = outerrow[0]
        cur.execute(nSql)
        # rest of your code
    

