【问题标题】:Insert into table using For In Range and keys of the value使用 For In Range 和值的键插入表中
【发布时间】:2017-08-29 18:10:04
【问题描述】:

我有一个填充数据的查询 (sql1),我正在尝试将此数据 (sql1) 的结果以及其他输入插入到同一个表中。

这是第一个查询(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()

我不确定底部代码是否正确(其中字段 %s 进入,其余字段)。

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 ) ' \

在这种情况下,我如何表达/完成类似于底部的内容(我还有两列要插入)?

我从其他帖子中获得了这个示例,但我不确定如何应用值的键。

抱歉,我需要一些关于我在这里做什么的指导。

 cursor.execute(sql2, (Cretor_Id, Record_Id, Course_Num, SiteCode), "UniqueCourseName", "")

【问题讨论】:

  • 你能打印(all[0])并告诉我返回什么
  • 我有一个结果元组 (1, '22222', 33, 'HN')
  • 所以,看看利奥波德的回答
  • 我不清楚这一点。那么,如何应用 leopold 的行结合 Insert 语句?
  • cursor.execute() 必须在for里面,你是用for来获取SELECT的每一列并添加到表中

标签: python mysql


【解决方案1】:

第二部分是正确的,但不要把这个( %s, %s, %s, %s, "UniqueCourseName", CURDATE() )用这个( %s, %s, %s, %s, %s, %s )和:

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

如果你 print(all[0]),你会看到类似

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

并且'Key'引用creator_id,因为它是一个字典。

如果返回一个元组则:

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

【讨论】:

  • 但我得到的错误是“TypeError: tuple indices must be integers, not str”
【解决方案2】:

你可以这样做:

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

fetchall() 应该返回一个元组列表。您可以在 for 循环中解包元组,以使代码更易于阅读。

另外,您似乎在Insert into Courses 之后缺少一个开头(

【讨论】:

  • fetchall() 返回一个字典,所以如果你这样做,它会在这种情况下将键添加到数据库中 creator_id、record_id、course_num、site_code 而不是值
  • @MauricioCortazar 我想这取决于你使用的是什么......这是我的假设:dev.mysql.com/doc/connector-python/en/…
  • 好吧,在这种情况下,OP 正在使用 pymysql 并且它返回一个字典,无论如何好点
  • @MauricioCortazar 我发布的链接是针对 pymysql 的。 Fetchall 返回一个元组列表...
  • 即 MySQL Connector/Python 与 pymysql 不同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2023-03-31
相关资源
最近更新 更多