Mysql数据库与Python

1、下载与安装mysql5.6
2、数据库的基本操做
3、python代码链接数据库
4、将爬虫信息保存到mysql数据库
1、下载与安装mysql5.6
下载和安装请看链接【MySQL数据库下载与安装详细教程】html

2、数据库的基本操做
cmd命令行下输入如下命令python

登录
mysql -u root -p
密码 (输本身安装时候设置的)
就能够看到登录成功的界面mysql


建立数据库
【python操做时候先要建立好数据库,因此这一步必不可少】
create database 数据库名 [其余选项];
例如咱们须要建立一个名为 samp_db 的数据库
create database samp_db
create database samp_db character set gbk;能够加上指定的编码类型sql

show databases; 命令查看已经建立了哪些数据库。数据库

两种方式对数据库进行使用的选择:
一:在登陆数据库时指定, 命令: mysql -D 所选择的数据库名 -h 主机名 -u 用户名 -p
例如登陆时选择刚刚建立的数据库: mysql -D samp_db -u root -p
二:在登陆后使用 use 语句指定, 命令: use 数据库名;
use 语句能够不加分号, 执行 use samp_db 来选择刚刚建立的数据库, 选择成功后会提示: Database changedapp

建立数据库表
使用 create table 语句可完成对表的建立, create table 的常见形式:
create table 表名称(列声明);
以建立 students 表为例, 表中将存放 学号(id)、姓名(name)、性别(sex)、年龄(age)、联系电话(tel) 这些内容:
create table students
(    
id int unsigned not null auto_increment primary key,
name char(100) not null,
sex char(10) not null,
age tinyint unsigned not null,
tel char(13) null default “-”
);编辑器

show variables like ‘char%’; 查看编码值工具

set names ‘gbk’; 更改编码(能够解决输入中文乱码状况)ui

show tables; 命令可查看已建立了表的名称;
describe 表名; 命令可查看已建立的表的详细信息。编码

插入信息
insert into students values(NULL, “王刚”, “男”, 20, “13811371377”);插入每列项的值的状况
insert into students (name, sex, age) values(“孙丽华”, “女”, 21);插入其中列的值

查看表信息
查表中的name,age的信息.
select name, age from students;

也可使用通配符 * 查询表中全部的内容, 语句:
select * from students;

以查询全部性别为女的信息为例, 输入查询语句:
select * from students where sex=“女”;

where 子句不只仅支持 “where 列名 = 值” 这种名等于值的查询形式, 对通常的比较运算的运算符都是支持的,
例如 =、>、<、>=、<、!= 以及一些扩展运算符 is [not] null、in、like 等等。
还能够对查询条件使用 or 和 and 进行组合查询

select * from students where id<5 and age>20;

更新表中的数据
使用示例:
将id为5的手机号改成默认的"-": update students set tel=default where id=5;
将全部人的年龄增长1: update students set age=age+1;
将手机号为 13288097888 的姓名改成 “张伟鹏”, 年龄改成 19: update students set name=“张伟鹏”, age=19 where tel=“13288097888”;

删除表中的数据
delete 语句用于删除表中的数据, 基本用法为:
delete from 表名称 where 删除条件;
使用示例:
删除id为2的行: delete from students where id=2;
删除全部年龄小于21岁的数据: delete from students where age<20;
删除表中的全部数据: delete from students;

建立后表的修改
添加列
在表的最后追加列 address: alter table students add address char(60);
在名为 age 的列后插入列 birthday: alter table students add birthday date after age;

修改列
基本形式: alter table 表名 change 列名称 列新名称 新数据类型;
示例:
将表 tel 列更名为 telphone: alter table students change tel telphone char(13) default “-”;
将 name 列的数据类型改成 char(16): alter table students change name name char(16) not null;

删除列
基本形式: alter table 表名 drop 列名称;
示例:
删除 birthday 列: alter table students drop birthday;

重命名表
基本形式: alter table 表名 rename 新表名;
示例:
重命名 students 表为 workmates: alter table students rename workmates;

删除整张表
基本形式: drop table 表名;
示例: 删除 workmates 表: drop table workmates;

删除整个数据库
基本形式: drop database 数据库名;
示例: 删除 samp_db 数据库: drop database samp_db;

修改 root 用户密码
使用 mysqladmin 方式:
打开命令提示符界面, 执行命令: mysqladmin -u root -p password 新密码
执行后提示输入旧密码完成密码修改, 当旧密码为空时直接按回车键确认便可。

可视化管理工具 MySQL Workbench
尽管咱们能够在命令提示符下经过一行行的输入或者经过重定向文件来执行mysql语句, 但该方式效率较低,
因为没有执行前的语法自动检查, 输入失误形成的一些错误的可能性会大大增长,
这时不妨试试一些可视化的MySQL数据库管理工具, MySQL Workbench
就是 MySQL 官方 为 MySQL 提供的一款可视化管理工具, 你能够在里面经过可视化的方式直接管理数据库中的内容,
而且 MySQL Workbench 的 SQL 脚本编辑器支持语法高亮以及输入时的语法检查, 固然, 它的功能强大, 毫不仅限于这两点。
MySQL Workbench官方介绍: http://www.mysql.com/products/workbench/
MySQL Workbench 下载页: http://dev.mysql.com/downloads/tools/workbench/

3、python代码链接数据库
一、安装pymysql库
cmd运行pip install pymysql

二、代码建表

import pymysql
db = pymysql.connect("localhost", "root", "admin", "test1")#admin为本身数据库密码,test1为本身cmd中建立的数据库名
cursor = db.cursor()
cursor.execute("drop table if exists fin;") #若是存在fin表时候先删除
sql = '''create table fin
    (    
        id int unsigned not null auto_increment primary key,
        姓名 char(100) not null,
        性别 char(4) not null,
        年龄 tinyint unsigned not null,
        电话 char(13) null default "-"
    );'''
cursor.execute(sql)
db.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
结果可在cmd命令行数据库中查看,如图:


3,代码向表中插入内容

import pymysql
db = pymysql.connect("localhost", "root", "admin", "test1")#admin为本身数据库密码,test1为本身cmd中建立的数据库名
cursor = db.cursor()
# cursor.execute("drop table if exists fin;") #若是存在fin表时候先删除
# sql = '''create table fin
#     (
#         id int unsigned not null auto_increment primary key,
#         姓名 char(100) not null,
#         性别 char(4) not null,
#         年龄 tinyint unsigned not null,
#         电话 char(13) null default "-"
#     );'''
# cursor.execute(sql)
name = '李白'
sex = '男'
age = '20'
tel = '123456789'
sql = "insert into fin (姓名,性别,年龄,电话) values ('%s','%s','%s','%s');" % (name, sex, age, tel)
cursor.execute(sql)
#为了遵循mysql语法也能够用如下两句字符串拼接
#sql = 'insert into fin  (姓名,性别,年龄,电话) values (\"'+name+'\",\"'+sex+'\",\"'+age+'\",\"'+tel+'\");'
#cursor.execute(sql)
db.commit()
db.close()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
结果如图:


4、将爬虫信息保存到mysql数据库
import requests
from bs4 import BeautifulSoup
import pymysql

list_url = []#存储生成的从第一页到第5页的网页链接
list_info_experience = []#存储求职要求经验
list_info_education = []#存储求职要求学历
list_info_money = []#存储求职要求薪资区间
list_name = []#存储求职公司名称
db = pymysql.connect("localhost", "root", "admin", "Myinterview")
cursor = db.cursor()

#mysql建表
def Create_Table(cursor):
    cursor.execute("drop table if exists employee;")  # 若是存在fin表时候先删除
    sql = '''create table employee
        (
            id int unsigned not null auto_increment primary key,
            公司名称 char(100) not null,
            工做经验 char(50) not null,
            学历要求 char(50) not null,
            薪资范围 char(50) null default "-"
        );'''
    cursor.execute(sql)

#插入爬取的信息
def Mysql_Content(cursor,JobName, JobExperience, JobEducation, JobMoney):
    print(JobName, JobExperience, JobEducation, JobMoney)
    sql = 'INSERT INTO employee(公司名称,工做经验,学历要求,薪资范围) VALUES (\"' + JobName + '\",\"' + JobExperience + '\",\"' + JobEducation + '\",\"' + JobMoney + '\")'
    #print(sql)
    cursor.execute(sql)
    db.commit()


#网页有不少页,这里把每一页的链接存储在list_url中
def Make_Url():
    for i in range(1, 4):
        global URL
        URL = 'https://www.jobui.com/jobs?jobKw=python&cityKw=%E5%8C%97%E4%BA%AC&n={}'.format(i)
        list_url.append(URL)
        #print(list_url)

#获取给定URL页的html信息
def Get_Wb(URL):

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
    wb_data = requests.get(URL, headers=headers)
    global soup
    soup = BeautifulSoup(wb_data.content, 'lxml')
    #print(soup)

#获取每家公司的名称
def Get_Name():
    names = soup.select('#search-match > div.header-2014 > div.astruct.cfix > div.aleft > div.jk-box.jk-matter.j-jobInfo > ul > li > div > div > div.cfix > a')
    for i in names:
        list_name.append(i.get_text().strip())

#获取每家公司的经验要求,学历要求,薪资区间
def Get_Msg():
    for i in range(1, 16):
        xxx = 'div.header-2014 > div.astruct.cfix > div.aleft > div.jk-box.jk-matter.j-jobInfo > ul > li:nth-of-type({}) > div > div > div:nth-of-type(4)'.format(i)
        #print(xxx)
        msg = soup.select(xxx)
        #print(msg)
        for y in msg:
            info = y.get_text()
            info = info.split('|')#将经验要求,学历要求,薪资区间3个信息,以|分割开,存储为列表格式
            list_info_experience.append(info[0].strip())
            list_info_education.append(info[1].strip())
            list_info_money.append(info[2].strip())
#最后以字典形式输出
def DictOutput():
    for JobName, JobExperience, JobEducation, JobMoney in zip(list_name, list_info_experience, list_info_education, list_info_money):

        AllData = {'公司名称': JobName,
                   '工做经验': JobExperience,
                   '学历要求': JobEducation,
                   '薪资范围': JobMoney
        }
        print(AllData)
        Mysql_Content(cursor, JobName, JobExperience, JobEducation, JobMoney)
print('北京市招聘信息')
Make_Url()
#先输出3页
for i in range(0, 3):
    Get_Wb(list_url[i])
    #print(list_url[i])#所爬取的网页连接
    Get_Msg()
    Get_Name()
Create_Table(cursor)
DictOutput()
db.close()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
结果如图:

------------------------------------------------------------------------ 谢谢支持! ---------------------  做者:Progial  来源:CSDN  原文:https://blog.csdn.net/qq_43371004/article/details/84182891   

相关文章
相关标签/搜索