0

TBL1 と TBL2 の 2 つのテーブルがあります。TBL1 には、date、id、nSql の 3 つの列があります。TBL2 には、date、custId、userId の 3 つの列があります。TBL1 に ID 1 から 17 までの 17 行があります (これは後で拡張されます)。各 nSql には SQL クエリが含まれています。たとえば、id=1 の nSql は次のとおりです。「select date、pId を custId として、tId を TBL3 からの userId として」 たとえば、id=2 の nSql は次のとおりです: 「select date、qId を custId として、rId を TBL4 からの userId として」結果は常に同じ 3 列です。

以下のクエリは、id =1 に対して nSql のみを実行します。したがって、TBL2 では、nSql =1 の出力しかありません。すべての nSql の結果が必要です。id =1 だけでなく、すべての nSql に対してクエリを実行したいと考えています。

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

2 に答える 2

0

すでにnSql結果を取得してループしています。両方をループする必要があります。

cur.execute(selectStatement)
res = cur.fetchall()
for outerrow in res:
    nSql = outerrow[0]
    cur.execute(nSql)
    # rest of your code
于 2013-03-28T00:24:44.897 に答える