Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - Insert into table using For In Range and keys of the value

I have a query (sql1) that populates data, and I am trying to insert the outcome of this data (sql1) as well as other inputs into same table.

Here is first query (sql1).

sql1 = ' Select Creator_Id, Record_Id, max(Course_Num) + 1, SiteCode ' 
       ' from ' 
       ' (Select Creator_Id, Record_Id, max(Course_Num) + 1, SiteCode from Courses ' 
       ' where ( Record_Id not in ("Test") ) ' 
       ' group by Record_Id '

cursor.execute(sql1)
all = cursor.fetchall()

I am not sure bottom code is correct (where fields %s comes in and rest fields).

for Creator_Id, Record_Id, Course_Num, SiteCode in all: 
    sql2 = ' Insert into Courses ' 
             ' ( Creator_Id, ' 
             '  Record_Id, ' 
             '  Course_Num, ' 
             '  SiteCode, ' 
                ' coursename, ' 
                ' datestamp ) ' 
           ' VALUES ' 
           ' ( %s, %s, %s, %s, %s, %s ) ' 

How do I express/complete something like on the bottom on this case (where I have two more columns to insert)?

I got this sample from other post, but not I am sure how to apply Key(s) of the value.

Sorry, I need some guidance regards to what I am doing here.

 cursor.execute(sql2, (Cretor_Id, Record_Id, Course_Num, SiteCode), "UniqueCourseName", "")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the second part is correct but instead of put this ( %s, %s, %s, %s, "UniqueCourseName", CURDATE() ) use this ( %s, %s, %s, %s, %s, %s ) and:

cursor.execute(sql2, (all[i]['Key1'], all[i]['Key2'], 
                       all[i]['Key3'], all[i]['Key4']),"UniqueCourseName", CURDATE())

if you print(all[0]), you will se something like

'Creator_Id' :'value1'
'Record_Id,':'value2'
' Course_Num':'value3'
             ' SiteCode':'value3'
               ' coursename ':'value4'
               ' datestamp':value5

and 'Key' make reference to creator_id, because is a dictionary.

if return a tuple then:

cursor.execute(sql2, (i[0], i[1], 
                       i[2], i[3]),"UniqueCourseName", CURDATE())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...