-1

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", "")
Java
  • 1,208
  • 3
  • 15
  • 29

2 Answers2

1

You can just do something like this:

for creator_id, record_id, course_num, site_code in all:
    cursor.execute(sql2, (creator_id, record_id, course_num, site_code))

fetchall() should return a list of tuples. You can unpack the tuples in the for loop to make the code easier to read.

Also, it looks like you're missing an opening ( after Insert into Courses

1

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())
Mauricio Cortazar
  • 4,049
  • 2
  • 17
  • 27