乐之之

知而行乐,乐而行之,天道酬勤,学无止境。
如何将爬取的数据保存至MySQL数据库里

python链接mysql数据库保存数据的步骤。

(1)创建表单。

create table vegetable_price
(
    id        int auto_increment
        primary key,
    prodCat   varchar(100) null,
    prodName  varchar(100) null,
    lowPrice  varchar(100) null,
    avgPrice  varchar(100) null,
    highPrice varchar(100) null,
    place     varchar(100) null,
    unitInfo  varchar(100) null
)
    charset = utf8mb3;

(2)连接数据库。

import pymysql
​
db = pymysql.Connect(
    host="127.0.0.1",
    port=3306,
    user="root",
    passwd="******",
    db="demo"
)
cursor = db.cursor()

(3)保存数据。

sql = "insert into Vegetable_price (prodCat,prodName,lowPrice,avgPrice,highPrice,place,unitInfo) values (%s,%s,%s,%s,%s,%s,%s)"
params = [(prodCat,prodName,lowPrice,avgPrice,highPrice,place,unitInfo)]
cursor.executemany(sql,params)
db.commit()

posted on 2022-11-21 23:29  乐之之  阅读(344)  评论(0编辑  收藏  举报