marsblues
marsblues
采纳率100%
2019-01-08 16:39

python如何把list中的字典结构 循环存储到MYSQL中?

5
  • list
  • python
已采纳

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)

如何把上面的list 中的字典 循环 存储到下面的表中

表的字段jie'gou"booksit","boname","auname","subname","subtype","bointro","charnu","uping","burl"

def ins_to_sql(self,sql):中我好像循环不出来,到sql中,感觉 没有从列表中把字典拿出来,谁能帮我再看看,谢谢!


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • qq_36720114 德玛洗牙 2年前

    import mysql.connector
    #数据库连接
    conn=mysql.connect.connector("连接参数")
    cursor=conn.cursor()
    for book_info in more_book_list:
    cursor.execute('insert into 表名 values(book_info['booksit'],...,book_info['burl'])')
    conn.commit()

    仅供参考,代码未补全,也不知道对不对

    点赞 1 评论 复制链接分享
  • weixin_39416561 lyhsdy 2年前

    ←如果以下回答对你有帮助,请点击右边的向上箭头及采纳下答案

    import pandas as pd
    from sqlalchemy import create_engine
    def tosql():   ##上传数据库
        # MySQL的用户:root, 密码:123456, 地址:10.10.0.92//(localhost)  端口:3306,数据库:test
        engine = create_engine('mysql+pymysql://root:123456@10.10.0.92:3306/test')
    
        df = pd.DataFrame(book_info)  ##book_info为字典结构数据
        df.to_sql('表名', con=engine, if_exists='append', index=False)    #if_exists='replace/append/fail'  append为插入
    
    
    点赞 2 评论 复制链接分享

相关推荐