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

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个回答

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()

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

marsblues
marsblues 能帮我再看一下吗,我补全了一些代码
11 个月之前 回复
marsblues
marsblues 你好,谢谢你的答案,我尝试一下后采纳,不行我把代码完整一点你到时再帮我看看
11 个月之前 回复

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

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为插入

marsblues
marsblues 我现在把 列表 里 的字典循环不出来,也插入不了
10 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!