У меня есть 2 таблицы TBL1 и TBL2. TBL1 имеет 3 столбца date, id, nSql. TBL2 имеет 3 столбца date, custId, userId. У меня есть 17 строк в TBL1 с id 1 до 17 (что будет расти позже). Каждый nSql имеет в нем SQL-запрос. Например, nSql для id = 1: «select date, pId as custId, tId as userId from TBL3» Например, nSql для id = 2: «select date, qId as custId, rId as userId из TBL4» . .. Результат nSql всегда одинаковый 3 столбца.Вставка данных в базу данных MySQL из Python
Ниже запроса выполняется только nSql для id = 1. Итак, в TBL2 у меня есть только вывод для nSql = 1. Я хочу результат для всех nSql. Я хочу, чтобы мой запрос выполнялся для всех nSql не только для 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()
Вам нужно будет получить результаты 'selectStatement' в цикле –
Я новичок в мире python. Я был бы признателен, если бы вы смогли показать его в коде. Спасибо! – Rio