数据库s4

Python之路【目录】
Python开发【第一篇】:目录
MySQL练习题参考答案

Day57

约法三章:
1. 课下不看视频
2. 笔记梗概
3. 课下整理上课内容

课程安排:
MySQL
Web框架:
- Python
- 前端
- MySQL
项目实战:
- 简单CURD
- 保障系统(博客+BBS+后台管理)
- CMDB资产管理
- CRM
- 堡垒机
爬虫:
- Scrapy
其他:
...

MySQL

单机程序(自己DB)

单机程序(公用DB)

MySQL:是用于管理文件的一个软件
    - 服务端软件
        - socket服务端
        - 本地文件操作
        - 解析指令【SQL语句】
    - 客户端软件(各种各样)
        - socket客户端
        - 发送指令
        - 解析指令【SQL语句】
    
    PS:
        - DBMS数据库管理系统
        - SQL语句
        
技能:
    - 安装 服务端和客户端
    - 连接
    - 学习SQL语句规则;指示服务端做任意操作
    

其他类似软件:
    关系型数据库:sqllite,db2,oracle,access,sql server MySQL
    非关系型数据库:MongoDB,redis
  1. MySQL安装

    Windows:
    可执行文件
    点点点
    压缩包
    放置任意目录
    初始化
    服务端:E:\wupeiqi\mysql-5.7.16-winx64\mysql-5.7.16-winx64\bin\mysqld --initialize-insecure
    # 用户名 root 密码:空
    启动服务端:
    E:\wupeiqi\mysql-5.7.16-winx64\mysql-5.7.16-winx64\bin\mysqld\mysqld

         客户端连接:
             E:\wupeiqi\mysql-5.7.16-winx64\mysql-5.7.16-winx64\bin\mysqld\mysql -u root -p 
             
             发送指令:
                 show databases;
                 create database db1;
             
         环境变量的配置:
             E:\wupeiqi\mysql-5.7.16-winx64\mysql-5.7.16-winx64\bin
             mysqld
             
         windows服务:
             E:\wupeiqi\mysql-5.7.16-winx64\mysql-5.7.16-winx64\bin\mysqld --install
             E:\wupeiqi\mysql-5.7.16-winx64\mysql-5.7.16-winx64\bin\mysqld --remove
             
             net start MySQL
             net stop MySQL
    
  2. 关于连接

    文件夹【数据库】
    文件【表】
    数据行【行】
    数据行
    数据行

    连接:

     默认:用户root
     
     
     show databases;
     
     use 数据库名称;
     
     show tables;
     
     select * from 表名;
     
     select name,age,id from 表名;
     
     mysql数据库user表
     use mysql;
     select user,host from user;
    
    
     创建用户:
           create user 'alex'@'192.168.1.1' identified by '123123';
           create user 'alex'@'192.168.1.%' identified by '123123';
           create user 'alex'@'%' identified by '123123';
     授权:
           权限  人
           
           grant select,insert,update  on db1.t1 to 'alex'@'%';
           grant all privileges  on db1.* to 'alex'@'%';
           
           revoke all privileges on db1.t1 from 'alex'@'%';
           
     DBA: 用户名密码
    
  3. 学习SQL语句规则

    操作文件夹
    create database db2;
    create database db2 default charset utf8; *****
    show databases;
    drop database db2;

    操作文件
    show tables;
    create table t1(id int,name char(10)) default charset=utf8;
    create table t1(id int,name char(10))engine=innodb default charset=utf8;
    create table t3(id int auto_increment,name char(10))engine=innodb default charset=utf8; *****

     create table t1(
         列名 类型 null,
         列名 类型 not null,
         列名 类型 not null auto_increment primary key,
         id int,
         name char(10)
     )engine=innodb default charset=utf8;
         # innodb 支持事务,原子性操作
         # myisam myisam
         
         auto_increment 表示:自增
         primary key:  表示 约束(不能重复且不能为空); 加速查找
         auto_increment和primary key是绑定关系,一个表只能设置一个
         not null: 是否为空
         数据类型:
             
             数字:
                 tinyint
                 int
                 bigint
                 
                 FLOAT
                     0.00000100000123000123001230123
                 DOUBLE
                     0.00000000000000000000100000123000123001230123
                     0.00000100000123000000000000000
                 decimal
                     0.1
                 
             字符串:
                 char(10)      速度快()
                     root      
                     root     
                 varchar(10)   节省空间
                     root
                 PS: 创建数据表把定长列往前放
                 
                 text
                 
                 上传文件: 
                     文件存硬盘
                     db存路径
             时间类型
                 DATETIME
         
             enum
             set
             
             
         create table t1(
             id int signed not null auto_increment primary key,
             num decimal(10,5),
             name char(10)
         )engine=innodb default charset=utf8;
     
     清空表:
         delete from t1;
         truncate table t1;
     删除表:
         drop table t1;
    

    操作文件中内容
    插入数据:
    insert into t1(id,name) values(1,'alex');
    删除:
    delete from t1 where id<6
    修改:
    update t1 set age=18;
    update t1 set age=18 where age=17;
    查看数据:
    select * from t1;

    外键:

     create table userinfo(
         uid int auto_increment primary key,
         name varchar(32),
         department_id int,
         xx_id int,
         constraint fk_user_depar foreign key (department_id) references department(id)
     )engine=innodb default charset=utf8;
     
     create table department(
         id bigint auto_increment primary key,
         title char(15)
     )engine=innodb default charset=utf8;
    

innodb原子操作

今日内容参考博客:
http://www.cnblogs.com/wupeiqi/articles/5713315.html
作业:
http://images2015.cnblogs.com/blog/425762/201608/425762-20160803224643778-2071849037.png
http://www.cnblogs.com/wupeiqi/articles/5729934.html
Day58

上节回顾:
1. 以ATM引出DBMS
2. MySQL
- 服务端
- 客户端
3. 通信交流
- 授权
- SQL语句
- 数据库
create database db1 default charset=utf8;
drop database db1;

        - 数据表
            先创建tb2部门表
                
            create table tb1用户表(
                id int not null auto_increment primary key,
                name char(10), --> 10为字符
                department_id int,
                p_id int,
                constraint fk_1 foreign key (department_id,p_id) references tb2(tid,xid)
            )engine=innodb default charset=utf8;
            
            
            补充:主键
                一个表只能有一个主键
                主键可以由多列组成
                
                
            补充:外键 ?
                CREATE TABLE t5 (
                  nid int(11) NOT NULL AUTO_INCREMENT,
                  pid int(11) not NULL,
                  num int(11),
                  primary key(nid,pid)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;



                create table t6(
                    id int auto_increment primary key,
                    name char(10),
                    id1 int,
                    id2 int,
                    CONSTRAINT fk_t5_t6 foreign key (id1,id2) REFERENCES t1(nid,pid)
                )engine=innodb default charset=utf8;
                                
            
            
        - 数据行
        
            insert into tb1(name,age) values('alex',18);
            insert into tb1(name,age) values('alex',18),('egon',19),('yuan',20);
            
            delete from tb1;
            truncate table tb1;
            delete from tb1 where id > 10
            
            
            update tb1 set name='root' where id > 10
            
            select * from tb;
            select id,name from tb;
        
        
4 对于自增补充:
    desc t10;
    
    show create table t10;
    
    show create table t10 \G;
    
    alter table t10 AUTO_INCREMENT=20;
        
        
    MySQL: 自增步长
        基于会话级别:
            show session variables like 'auto_inc%';    查看全局变量
            set session auto_increment_increment=2;     设置会话步长
            # set session auto_increment_offset=10;
        基于全局级别:
            show global variables like 'auto_inc%';     查看全局变量
            set global auto_increment_increment=2;      设置会话步长
            # set global auto_increment_offset=10;
            
            
    SqlServer:自增步长:
        基础表级别:
            CREATE TABLE `t5` (
              `nid` int(11) NOT NULL AUTO_INCREMENT,
              `pid` int(11) NOT NULL,
              `num` int(11) DEFAULT NULL,
              PRIMARY KEY (`nid`,`pid`)
            ) ENGINE=InnoDB AUTO_INCREMENT=4, 步长=2 DEFAULT CHARSET=utf8
            
            CREATE TABLE `t6` (
              `nid` int(11) NOT NULL AUTO_INCREMENT,
              `pid` int(11) NOT NULL,
              `num` int(11) DEFAULT NULL,
              PRIMARY KEY (`nid`,`pid`)
            ) ENGINE=InnoDB AUTO_INCREMENT=4, 步长=20 DEFAULT CHARSET=utf8

今日内容:
0. 唯一索引

    create table t1(
        id int ....,
        num int,
        xx int,
        unique 唯一索引名称 (列名,列名),  #联合唯一
        constraint ....
    )
    # 
    1   1   1
    2   1   2
    PS: 
        唯一:
            约束不能重复(可以为空)
            PS: 主键不能重复(不能为空)
        加速查找

1. 外键的变种
    
    a. 用户表和部门表
    
        用户:
            1 alex     1
            2 root     1
            3 egon     2
            4 laoyao   3
            
        部门:
            1 服务
            2 保安
            3 公关
        ===》 一对多
    b. 用户表和博客表
        用户表:
            1 alex    
            2 root     
            3 egon     
            4 laoyao   
        博客表:
                              FK() + 唯一
            1   /yuanchenqi/   4
            2    /alex3714/    1
            3    /asdfasdf/    3
            4    /ffffffff/    2
            
        ===> 一对一
        
            create table userinfo1(
                id int auto_increment primary key,
                name char(10),
                gender char(10),
                email varchar(64)
            )engine=innodb default charset=utf8;

            create table admin(
                id int not null auto_increment primary key,
                username varchar(64) not null,
                password VARCHAR(64) not null,
                user_id int not null,
                unique uq_u1 (user_id),
                CONSTRAINT fk_admin_u1 FOREIGN key (user_id) REFERENCES userinfo1(id)
            )engine=innodb default charset=utf8;

        
        
        
    c. 用户表(百合网) 相亲记录表
    
        示例1:
            用户表
            相亲表
            
        示例2:
            用户表
            主机表
            用户主机关系表
        ===》多对多

            create table userinfo2(
                id int auto_increment primary key,
                name char(10),
                gender char(10),
                email varchar(64)
            )engine=innodb default charset=utf8;

            create table host(
                id int auto_increment primary key,
                hostname char(64)
            )engine=innodb default charset=utf8;


            create table user2host(
                id int auto_increment primary key,
                userid int not null,
                hostid int not null,
                unique uq_user_host (userid,hostid),
                CONSTRAINT fk_u2h_user FOREIGN key (userid) REFERENCES userinfo2(id),
                CONSTRAINT fk_u2h_host FOREIGN key (hostid) REFERENCES host(id)
            )engine=innodb default charset=utf8;
                
                
2. SQL语句数据行操作补充
        create table tb12(
            id int auto_increment primary key,
            name varchar(32),
            age int
        )engine=innodb default charset=utf8;

    增
        insert into tb11(name,age) values('alex',12);
        
        insert into tb11(name,age) values('alex',12),('root',18);
        
        insert into tb12(name,age) select name,age from tb11;
    删
        delete from tb12;
        delete from tb12 where id !=2 
        delete from tb12 where id =2 
        delete from tb12 where id > 2 
        delete from tb12 where id >=2 
        delete from tb12 where id >=2 or name='alex'
    
    改
        update tb12 set name='alex' where id>12 and name='xx'
        update tb12 set name='alex',age=19 where id>12 and name='xx'
    查
        
        select * from tb12;
        
        select id,name from tb12;
        
        select id,name from tb12 where id > 10 or name ='xxx';
        
        select id,name as cname from tb12 where id > 10 or name ='xxx';
        
        select name,age,11 from tb12;
        
        其他:
            select * from tb12 where id != 1
            select * from tb12 where id in (1,5,12);
            select * from tb12 where id not in (1,5,12);
            select * from tb12 where id in (select id from tb11)
            select * from tb12 where id between 5 and 12; -- 闭区间

        
            通配符:
            
            select * from tb12 where name like "a%"
            select * from tb12 where name like "a_"

        
            分页:
            
                select * from tb12 limit 10;
                
                select * from tb12 limit 0,10;
                select * from tb12 limit 10,10;
                select * from tb12 limit 20,10;
                
                select * from tb12 limit 10 offset 20;
                从第20行开始读取,读取10行;
    
                结合Python分页:
                # page = input('请输入要查看的页码')
                # page = int(page)
                # (page-1) * 10
                # select * from tb12 limit 0,10; 1 
                # select * from tb12 limit 10,10;2
            
            
            排序:
                select * from tb12 order by id desc; 大到小
                select * from tb12 order by id asc;  小到大
                 select * from tb12 order by age desc,id desc;
                 
                取后10条数据
                select * from tb12 order by id desc limit 10;
        
            分组:
            
                select count(id),max(id),part_id from userinfo5 group by part_id;
                
                count
                max
                min
                sum
                avg
                
                **** 如果对于聚合函数结果进行二次筛选时?必须使用having ****
                select count(id),part_id from userinfo5 group by part_id having count(id) > 1;
                
                select count(id),part_id from userinfo5 where id > 0 group by part_id having count(id) > 1;
        
                
            连表操作:
            
                select * from userinfo5,department5
                
                select * from userinfo5,department5 where userinfo5.part_id = department5.id
                

                select * from userinfo5 left join department5 on userinfo5.part_id = department5.id
                select * from department5 left join userinfo5 on userinfo5.part_id = department5.id
                # userinfo5左边全部显示
                
                
                # select * from userinfo5 right join department5 on userinfo5.part_id = department5.id
                # department5右边全部显示
            
            
            
                select * from userinfo5 innder join department5 on userinfo5.part_id = department5.id
                将出现null时一行隐藏
                
                
            
            
            
            
                select * from 
                    department5 
                left join userinfo5 on userinfo5.part_id = department5.id
                left join userinfo6 on userinfo5.part_id = department5.id
            
            
                select 
                    score.sid,
                    student.sid 
                    from 
                score

                    left join student on score.student_id = student.sid

                    left join course on score.course_id = course.cid

                    left join class on student.class_id = class.cid

                    left join teacher on course.teacher_id=teacher.tid
                
        
        
        
        select count(id) from userinfo5;

作业练习:
http://www.cnblogs.com/wupeiqi/articles/5729934.html
10-15个完成
day59

数据库s4_第1张图片
59.jpg

临时表
select sid from (select * from score where num > 60) as B;
(select * from score where num > 60) as B;
2、查询“生物”课程比“物理”课程成绩高的所有学生的学号;
select A.student_id from (select score.sid,score.student_id,course.cname,score.num from score left join course on score.course_id=course.cid where course.cname="生物") as A inner join (select score.sid,score.student_id,course.cname,score.num from score left join course on score.course_id=course.cid where course.cname="物理") as B on A.student_id = B.student_id where A.num > B.num;
3、查询平均成绩大于60分的同学的学号和平均成绩;
select student_id,avg(num) from score group by student_id having avg(num)>60;
在此基础上显示学生的姓名
select B.student_id,student.sname,B.cccc from (select student_id,avg(num) as cccc from score group by student_id having avg(num)>60) as B left join student on B.student_id = student.sid;
4、查询所有同学的学号、姓名、选课数、总成绩;
select score.student_id,student.sname,count(1),sum(num) from score left join student on score.student_id=student.sid group by score.student_id;
5、查询姓“李”的老师的个数;
select count(1) from teacher where tname like "李%";
select count(tid) from teacher where tname like '李%';
6、查询没学过“叶平”老师课的同学的学号、姓名;
select student.sid,student.sname from student where sid not in (select student_id from score where course_id in (select course.cid from course left join teacher on course.teacher_id = teacher.tid where teacher.tname = "李平老师") group by student_id);

pymysql

# SQL注入
import pymysql

user = input("username:")
pwd = input("password:")

conn = pymysql.connect(host="localhost",user="root",password="",database="db666")
cursor = conn.cursor()
# sql = "select * from userinfo where username='%s' and password='%s'" %(user,pwd,) #不要使用这种方式
# sql = "select * from userinfo where username='uu'or 1=1 -- ' and password='%s'" %(user,pwd,) --空格 会注释掉后面的东西
# print(sql)
#3种方式,字典和列表形式可以用,中间的那种会报错
sql = "select * from userinfo where username=%(u)s and password=%(p)s"
cursor.execute(sql,{'u':user,'p':pwd})
# sql = "select * from userinfo where username=%s and password=%s" #这种会报错
# cursor.execute(sql,user,pwd) #TypeError: execute() takes from 2 to 3 positional arguments but 4 were given
# sql = "select * from userinfo where username=%s and password=%s"
# cursor.execute(sql,[user,pwd])
result = cursor.fetchone()   返回单个的元组,也就是一条记录(row),如果没有结果 则返回 None
cursor.close()
conn.close()
print(result)

if result:
    print('登陆成功')
else:
    print('登陆失败')

增 删 改

import pymysql
#增加

conn = pymysql.connect(host="localhost",user="root",password="",database="db666")
cursor = conn.cursor()
sql = "insert into userinfo(username,password) values('root','123123')" # root和123123那里只能是单引号
r = cursor.execute(sql) # r表示受影响的行数
conn.commit() # 涉及到增删改的时候需要commit
cursor.close()
conn.close()
import pymysql
#增加
# user = "eric"
# pwd = "123123"
conn = pymysql.connect(host="localhost",user="root",password="",database="db666")
cursor = conn.cursor()
# sql = "insert into userinfo(username,password) values(%s,%s)"
# cursor.execute(sql,[user,pwd]) # 列表元组都可以
sql = "insert into userinfo(username,password) values(%s,%s)" # 增加多条
r = cursor.executemany(sql,[('egon','sb'),('laoyao','BS')]) # r表示受影响的行数
conn.commit() # 涉及到增删改的时候需要commit
cursor.close()
conn.close()

import pymysql
# 查
# cursor.scroll(1,mode='relative')  # 相对当前位置移动
# cursor.scroll(2,mode='absolute') # 相对绝对位置移动
conn = pymysql.connect(host="localhost",user="root",password="",database="db666")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #括号里面的参数不加返回元组里面套元组,加了返回列表里面套字典

sql = "select * from userinfo"
cursor.execute(sql)
# result = cursor.fetchone() # 获取一条
# print(result)
# result = cursor.fetchmany(3) # 获取多条
# print(result)
result = cursor.fetchall() # 获取全部
print(result)
cursor.close()
conn.close()

你可能感兴趣的:(数据库s4)