首页 > 技术文章 > 10-爬虫数据存取-MySQL处理

REN-Murphy 2021-04-15 16:15 原文

MySQL数据库安装

安装教程:https://blog.csdn.net/bobo553443/article/details/81383194

下载那个版本视自己的操作系统和项目要求,不同版本区别不大,建议安装5.6.或者5.7.稳定版本(这里我用的版本是5.7.33.0)

 

Navicat for MySQL数据库管理软件

安装教程:https://blog.csdn.net/cnds123321/article/details/105704886

 

相关文档

链接:https://pan.baidu.com/s/1RE36MhnXZNkm9fggfHl8aA
提取码:7wdq
复制这段内容后打开百度网盘手机App,操作更方便哦

 

驱动程序
Python想要操作MySQL。必须要有一个中间件,或者叫做驱动程序。驱动程序有很多。比如有:
1.mysqldb(只在Python2中有用)
2.Mysqlclient
3.Pymysql

在这里,我们选择用pymysql。安装方式也是非常简单,通过命令:
pip install pymysql

 

python连接mysql
db = pymysql.connect(host="127.0.0.1",user="root",password="password",database="pymysql_test",charset="utf8",port=3306)

host:以后在连接外网服务器的时候,就要改成外网服务器的ip地址
port:在外网一般会更换端口号,不会为3306,这是为了安全考虑
user:连接的用户,一般在生产环境中会单独分配一个账号给你,而不是使用root用户
database:要连接操作的数据库名
charset:设置为utf8这样就能操作中文了

# python连接mysql

import pymysql

title = ""+input("请输入书名:")+""
content = input("请输入书中的精彩片段:")

# 注意:是charset="utf8",而不是"utf-8"
db = pymysql.connect(host="127.0.0.1",user="root",password="password",database="pymysql_test",charset="utf8",port=3306)

# 创建游标对象(通过游标对数据库进行操作)
cursor = db.cursor()

# 执行sql语句(将数据插入到article表中)
cursor.execute("insert into article set title='{}', content='{}'".format(title,content))
cursor.execute("select * from article")

# 查询表carpark里面的数据,并返回二维数据类型
data = cursor.fetchall()
print(data)

# 提交到数据库
db.commit()

# 关闭游标,关闭连接
cursor.close()  
db.close()  

 

 

1.MySQL插入数据

第一种方式:

INSERT INTO 表名 SET 列名称 = 列值

第二种方式:

INSERT INTO 表名 VALUES(值1, 值2,....)
INSERT INTO 表名(列1, 列2,...) VALUES (值1, 值2,....)

# 插入数据

import pymysql

db = pymysql.connect(host="127.0.0.1",user="root",password="password",database="pymysql_test",charset="utf8",port=3306)
cursor = db.cursor()

# 1.第一种插入数据的方法
title_1 = "《艳阳天》"
content_1 = "五月末的北方夜晚,是最清新、最美好的时刻.天空象是刷洗过一般,没有一丝云雾,蓝晶晶的,又高又远.一轮圆圆的月亮,从东边的山梁上爬出来,如同一盏大灯笼,把个奇石密布的山谷照得亮堂堂,把树枝、幼草的影投射在小路上,花花点点,悠悠荡荡.宿鸟在枝头上叫着,小虫子在草棵子里蹦着,梯田里春苗在拔秆儿生长着;山野中也有万千生命在欢腾着……"

cursor.execute("insert into article set title='{}',content='{}'".format(title_1,content_1))
db.commit()
print("第一种方式写入成功!")

# 2.第二种插入数据的方法
title_2 = "《秋河》"
content_2 = "月光洒满了这园庭,远处的树林,顶上载着银色的光华,林里烘出浓厚的黑影,寂静严肃的压在那里.喷水池的喷水,池里的微波,都反射着皎洁的月光,在那里荡漾,她脚下的绿茵和近旁的花草也披了月光,柔软无声的在受她的践踏."

sql = "insert into article(id,title,content) values(null,%s,%s)"
cursor.execute(sql,(title_2,content_2))
db.commit()
print("第二种方式写入成功!")

cursor.close()  
db.close() 

2.MySQL删除数据

DELETE FROM 表名 WHERE 列名称 = 值

# 删除数据

import pymysql

db = pymysql.connect(host="127.0.0.1",user="root",password="password",database="pymysql_test",charset="utf8",port=3306)
cursor = db.cursor()

# 删除article表中指定数据
title = ""+input("请输入要删除的书名:")+""
print("正在删除删除标题为{}的数据...".format(title))
cursor.execute("delete from article where title ='{}'".format(title))
db.commit()
print("删除成功!")

cursor.close()  
db.close()

3.MySQL更改数据

UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值

# 更新数据

import pymysql

db = pymysql.connect(host="127.0.0.1",user="root",password="password",database="pymysql_test",charset="utf8",port=3306)
cursor = db.cursor()

# 更新article表中指定数据
title = ""+input("请输入要修改的书名:")+""
title_1 = ""+input("请输入修改后的书名:")+""
content_1 = input("请输入修改后的书中精彩片段:")
cursor.execute("update article set title='{1}',content='{2}'where title='{0}'".format(title,title_1,content_1))
cursor.execute("select *  from article where title='{}'".format(title_1))
data = cursor.fetchone()
print("数据修改为:",data)
db.commit()

cursor.close()  
db.close()

4.MySQL查找数据

SELECT * FROM 表名
SELECT 列名称 FROM 表名 (WHERE 列名称 = 某值)

扩展:使用pymysql查询数据,可以使用以下方法

fetchone():这个方法每次只获取一条数据

fetchall():这个方法接收全部的返回结果

fetchmany(size):可以获取指定条数的数据

# 查找数据

import pymysql

db = pymysql.connect(host="127.0.0.1",user="root",password="password",database="pymysql_test",charset="utf8",port=3306)
cursor = db.cursor()

# fetchone()函数,这个方法每次只获取一条数据
title = ""+input("请输入要查找书的名字:")+""
cursor.execute("select content from article where title='{}'".format(title))
content = cursor.fetchone()
print("\nfetchone()函数:",content)
db.commit()

# fetchall()函数,这个方法接收全部的返回结果
cursor.execute("select * from article")
content = cursor.fetchall()
print("\nfetchall()函数:",content)
db.commit()

# fetchmany(size)函数,可以获取指定条数的数据,指定两条数据
cursor.execute("select * from article")
content = cursor.fetchmany(2)
print("\nfetchmany()函数:",content)
db.commit()

cursor.close()  
db.close()

 

对上述python中连接MySQL代码进行封装

#coding=utf-8
import pymysql

class mysqlSearch(object):
    def __init__(self):
        self.get_conn()

    def get_conn(self):
        try:
            self.conn = pymysql.connect(
                host='localhost',
                user='root',
                password='password',
                database='pymysql_test',
                port=3306,
                charset='utf8',
            )
        except pymysql.Error as e:
            print(e)

    def close_conn(self):
        try:
            if self.conn:
                # 关闭连接
                self.conn.close()
        except pymysql.Error as e:
            print(e)

    def get_one(self):
        # 准备sql
        sql = "select * from news where author= %s order by create_time desc;"
        # 找到cursor
        cursor = self.conn.cursor()
        # 执行sql
        cursor.execute(sql,('大苏打'))
        # 输出结果
        rest = cursor.fetchall()
        #输出数据行
        print(cursor.rowcount)
        #处理数据
        print(rest)
        #关闭cursor/连接
        cursor.close()
        self.close_conn()

    # 添加一条数据
    def add_one(self):
        pass
        #准备sq
        #获取cursor

def main():
    obj=mysqlSearch()
    obj.get_one()

if __name__=='__main__':
    main()

 

推荐阅读