怎么把爬虫的数据导入mysql

2023年 11月 11日 25.4k 0

如何将爬虫数据导入MySQL数据库?以下是一些简单步骤。

怎么把爬虫的数据导入mysql

1. 确保创建了MySQL数据库,并安装了Python。

2. 使用Python中的MySQL连接器,如mysql-connector-python或PyMySQL。

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
mycursor = mydb.cursor()

3. 将抓取的数据存储在一个Python列表中。

data = [("apple", "fruit", 1.99),
("banana", "fruit", 0.99),
("carrot", "vegetable", 0.49)]

4. 使用INSERT语句将数据插入MySQL表中。

for item in data:
sql = "INSERT INTO products (name, category, price) VALUES (%s, %s, %s)"
val = item
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

上述代码将在名为products的MySQL表中插入所有数据。

在这个简单的教程中,你已经学会了如何将Python爬虫数据导入到MySQL数据库中。请记住,在实际应用中,你应该更好地处理异常情况,并确保代码的安全性和完整性。

相关文章

Oracle如何使用授予和撤销权限的语法和示例
Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
社区版oceanbase安装
Oracle 导出CSV工具-sqluldr2
ETL数据集成丨快速将MySQL数据迁移至Doris数据库

发布评论