15_爬虫数据入库

在这里插入图片描述


博文配套视频课程:24小时实现从零到AI人工智能


首先下载mysql驱动

C:\Users\Administrator>pip install mysql
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting mysql
Requirement already satisfied: mysqlclient in d:\anaconda3\lib\site-packages (from mysql) (1.4.2.post1)
Installing collected packages: mysql
Successfully installed mysql-0.0.2

python连接mysql数据库

import pymysql
# 连接数据库
db = pymysql.connect(host="127.0.0.1",user="root",password="root",database="mysql")
# connection
print(db)
# 所有的操作都需要通过游标来执行
cursor = db.cursor()

数据插入操作

try:
    sql = "insert into article (title, name, url, collection) values (%s,%s,%s,%s)"
    # 通过游标完成CRUD
    cursor.execute(sql,('我是标题','作者名称','url地址','文艺、科技、娱乐'))
    # 默认需要手动提交事务
    db.commit()
except:
    print('sql插入出错')
    db.rollback()
finally:
    cursor.close()
    db.close()

数据更新操作

cursor = db.cursor()
# 数据的插入操作  db  file url 都需要异常的捕获
try:
    sql = "update article set title=%s, name=%s where id=%s"
    # 返回的是受影响的行数
    count = cursor.execute(sql,('新标题2','老作者2',3))
    print('更新的行数为',count)
    # 默认需要手动提交事务
    db.commit()
except:
    print('sql更新出错')
    db.rollback()

数据查询操作

cursor = db.cursor()
# 数据的插入操作  db  file url 都需要异常的捕获
try:
    sql = "select * from article where id= %s "
    # 返回的是受影响的行数
    count = cursor.execute(sql,3)
    print('查询的记录数为',count)
    # 查询不需要提交事务,但是要通过fetch完成数据的抓取
    print(cursor.fetchone())
except:
    print('sql查询出错')

查询分页实现

cursor = db.cursor()
try:
    keyword = '标题'
    current_page = 1
    size = 3
    sql = "select * from article where title like %s limit %s,%s"
    # 返回的是受影响的行数
    count = cursor.execute(sql,(f'%{keyword}%',(current_page-1)*size,size))
    print('查询的记录数为',count)
    # 查询不需要提交事务,但是要通过fetch完成数据的抓取
    for row in cursor.fetchall():
        print(row)
except:
    print('sql查询分页出错')

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值