数据存储:Python对MySQL数据库操作

安装mysql

官网下载地址:https://dev.mysql.com/downloads/windows/installer/5.7.html

如果提示没有.NET Framework框架,在提示框中找到下载链接,下载一个就可以了。

如果提示没有Microsoft Virtual C++ x64(x86),百度或谷歌一下这个软件,安装即可。

navicat

navicat是一个操作mysql数据库非常方便的可视化软件,使用它操作数据库,就像excel一样的简单。

安装驱动程序

Python要想操作MySQL,必须要有一个中间件,或者叫做驱动程序。

驱动程序有很多,如:mysqldb、mysqlclient、pymysql等。这里选择用pymysql。

安装方式和安全其他库一样,非常简单,通过命令pip install pymysql即可安装。

数据库连接

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='密码', database='pymysql_demo', port=3306)

cursor = conn.cursor()          # 创建一个游标

cursor.execute('select 1')      # 连接数据库并执行数据库语句:'select 1' 表示 连接成功返回1
result = cursor.fetchone()      # 执行语句后返回的结果
print(result)

conn.close()                    # 关闭连接

插入数据

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='密码', database='pymysql_demo', port=3306)

cursor = conn.cursor()          # 创建一个游标

sql = """
insert into user(id, username, age, password) values(3, 'bbb', 20, '111111')
"""  # 定义要插入的字段:id username age password和对应的值:3 bbb 20 111111

cursor.execute(sql)             # 连接数据库并执行sql语句

conn.commit()  # 提交;插入(增)、删除、更改、都需要执行commit操作


# 上面的代码把传入的值写死了,因为每次传的值是不一样的,所以不能是固定的,这里要使用占位符
sql = """
insert into user(id, username, age, password) values(null, %s, %s, %s)
"""         # id设置为null它会自动增长,其他数据都是用%s字符串方式(即使在创建数据库的时候用的是其他类型)

username = 'bbb'
age = 21
password = '123456'

cursor.execute(sql, (username, age, password))  # 连接数据库并执行sql语句,传入一个元祖里面放入要插入的字段所对应的值

conn.commit()  # 插入(增)、删除、更改、都需要执行commit操作


conn.close()                    # 关闭连接

把爬取到的文章插入到网站MySql数据库里

# emlog


import pymysql


def connetSql():
    sqlConnect = pymysql.connect(
        user='my_blog', password='TjwBdbLEH4pExdSC', host='103.00.00.00', database='my_blog', charset='utf8', port=3306
    )
    cursor = sqlConnect.cursor()  # 创建操作游标
    return cursor, sqlConnect


cursor, conn = connetSql()


def executeSql(title, date, content, sortid, excerpt='', alias='', author=1, views=800):
    """插入   文章标题 时间戳 文章内容 文章分类 文章摘要   文章别名    发布者    阅读数量"""

    sql = """
    insert into emlog_CaiJing_blog(gid, title, date, content, sortid, excerpt, alias, author, views)
    values(null, %s, %s, %s, %s, %s, %s, %s, %s)
    """

    cursor.execute(sql, (title, date, content, sortid, excerpt, alias, author, views))

    conn.commit()  # 插入(增)、删除、更改、都需要执行commit操作
    # conn.close()                    # 关闭连接


def reConnect():
    # 有时候会用到  cursor.connection.ping()
    try:
        cursor.connection.ping()
    except:
        cursor.connection.ping()
# zblog


import pymysql


def connetSql():
    sqlConnect = pymysql.connect(
        user='my_blog_', password='zebGh8n5se', host='103.00.00.00', database='my_blog_', charset='utf8', port=3306
    )
    cursor = sqlConnect.cursor()  # 创建操作游标
    # sqlConnect.ping(True)  # 应该同于def reConnect():里的ping
    return cursor, sqlConnect


cursor, conn = connetSql()


def executeSql(log_CateID, log_Title, log_Content, log_PostTime, log_ViewNums=800, log_Tag='',
               log_AuthorID=1,  log_Status=0, log_Type=0, log_Intro=''):
    """插入   log_CateID:分类id  log_AuthorID:作者 1  log_Tag:标签 {标签id}  log_Status:状态 0
             log_Type:类型 0是文章 1是页面  log_Title:标题  log_Intro:摘要
            log_Content:内容  log_PostTime:时间戳  log_ViewNums:阅读数量"""

    sql = """
    insert into zbp_post(log_ID, log_CateID, log_Title, log_Content, log_PostTime, log_ViewNums, log_Tag,
    log_AuthorID,  log_Status, log_Type, log_Intro)
    values(null, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    """

    cursor.execute(sql, (log_CateID, log_Title, log_Content, log_PostTime, log_ViewNums, log_Tag,
                         log_AuthorID,  log_Status, log_Type, log_Intro))

    conn.commit()  # 插入(增)、删除、更改、都需要执行commit操作
    # conn.close()                    # 关闭连接


def reConnect():
    # 有时候会用到  cursor.connection.ping()
    try:
        cursor.connection.ping()
    except:
        cursor.connection.ping()

ping()

sql = "insert into aaa(id, a, b, c, d) values(%s,%s,%s,%s,%s)"
while True:
    try:
        with connect.cursor() as cursor:  # 获取游标
            cursor.execute(sql, (id01, a, b[0], c[1], d))
        connect.commit()
        break
    except Exception:
        connect.ping(True)

查找数据

三种方式

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='密码', database='pymysql_demo', port=3306)

cursor = conn.cursor()          # 创建一个游标


'''1、.fetchone() 查找一个字段'''

sql = """
select username, age from user where id=2
"""     # 要查找的字段:username和age 在user这张表里 需满足条件:id=2

cursor.execute(sql)             # 连接数据库并执行sql语句
result = cursor.fetchone()      # .fetchone() 只会返回一条数据
print(result)


sql = """
select * from user
"""     # 要查找的字段:所有字段(*) 在user这张表里 需满足条件:不指定(查找所有)

cursor.execute(sql)             # 连接数据库并执行sql语句
while True:
    result = cursor.fetchone()  # .fetchone() 只会返回一条数据,但是可以使用while死循环打印所有的出来就跟.fetchall()一样效果了
    if result:                  # 如果result不为空
        print(result)           # 执行打印
    else:                       # 否则跳出循环
        break


'''2、.fetchall() 查找所有字段'''

sql = """
select * from user
"""     # 要查找的字段:所有字段 在user这张表里 需满足条件:不指定

cursor.execute(sql)             # 连接数据库并执行sql语句
results = cursor.fetchall()     # .fetchall() 会返回所有数据
for result in results:
    print(result)


'''3、.fetchmany() 查找指定数量字段'''

sql = """
select * from user
"""     # 要查找的字段:所有字段 在user这张表里 需满足条件:不指定

cursor.execute(sql)
results = cursor.fetchmany(3)     # .fetchmany(3):返回3条数据
for result in results:
    print(result)


conn.close()

更改数据和删除数据

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='密码', database='pymysql_demo', port=3306)

cursor = conn.cursor()          # 创建一个游标


'''删除数据'''
sql = """
delete from user where id=1
"""  # 删除id为1的字段(一般都是直接删除整行)

cursor.execute(sql)         # 执行

# 插入、删除、更改、都需要执行commit操作
conn.commit()


'''更改数据'''
sql = """
update user set username='aaa' where id=2
"""     # 不加条件where id=2 会把所有字段的username改为aaa

cursor.execute(sql)         # 连接数据库并执行sql语句

# 插入、删除、更新、都需要执行commit操作
conn.commit()


conn.close()

你可能感兴趣的:(网络爬虫,数据库,mysql,python,sql,java)