marsblues
2019-01-10 21:07
采纳率: 100%
浏览 501

python 无法把列表中的字典结构循环 插入到MYSLQ表的字段中,帮忙看下

贴上了部分代码, 无法把列表中的字典插入到数据表中
import codecs
import MySQLdb
def get_book_info(self,text):
more_book_list =[]
for i in range(20):
book_info = {}
book_info["booksit"] = url_book_list[i] if boname_list else None
book_info["boname"] = boname_list[i] if boname_list else None

   book_info["auname"] = auname_list[i] if auname_list else None

   book_info["subname"] = subname_list[i] if subname_list else None

   book_info["subtype"] = subtype_list[i] if subtype_list else None

   book_info["bointro"] = bointro_list[i] if bointro_list else None

   book_info["charnu"] = charnu_list[i] if charnu_list else None

   book_info["uping"] = uping_list[i] if uping_list else None

   book_info["burl"] = burl_list[i] if burl_list else None

   more_book_list.append(book_info)

return more_book_list

def ins_to_sql(self,sql):
conn=MySQLdb.connect("127.0.0.1", "root", "usbw", "carwbook", 3307 )
cursor=conn.cursor()

for book_info in sql:

    cursor.execute('INSERT INTO booktable(boname,auname,subname,subtype,bointro,charnu,uping,burl) VALUES (book_info["boname"],book_info["auname"],book_info["subname"],book_info["subtype"],book_info["bointro"],book_info["charnu"],book_info["uping"],book_info["burl"])')

conn.commit()
conn.close()

if name == '__main__':
url = 'https://www'
text = book.get_html(url)
sql = book.get_book_info(text)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • lyhsdy 2019-01-11 12:04
    已采纳
    
    for book_info in sql:
            sql='INSERT INTO booktable(boname,auname,subname,subtype,bointro,charnu,uping,burl) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s ))' %(book_info["boname"],book_info["auname"],book_info["subname"],book_info["subtype"],book_info["bointro"],book_info["charnu"],book_info["uping"],book_info["burl"])
        cursor.execute(sql)
    
    conn.commit()
    conn.close()
    
    点赞 评论
  • eagle1024 2019-01-10 22:00

    不能这么粗暴的插入,试试这种方法,把你的insert语句改造一下
    book_info_tup=(book_info["boname"],book_info["auname"],book_info["subname"],book_info["subtype"],book_info["bointro"],book_info["charnu"],book_info["uping"],book_info["burl"])
    sql='INSERT INTO booktable(boname,auname,subname,subtype,bointro,charnu,uping,burl) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s ))' %book_info_tup
    cursor.execute(sql)

    点赞 评论
  • manyu1026 2019-01-10 22:07

    报什么错呢,可以报错误信息贴一下吗

    点赞 评论

相关推荐 更多相似问题