• mysql数据库


    1.一些多表查询的练习题

    2.pymysql模块

    3.sql注入问题 

    4.增删改查

    一.一些多表查询的练习题

    首先用Navicat导入数据:

      1 /*
      2  数据导入:
      3  Navicat Premium Data Transfer
      4 
      5  Source Server         : localhost
      6  Source Server Type    : MySQL
      7  Source Server Version : 50624
      8  Source Host           : localhost
      9  Source Database       : sqlexam
     10 
     11  Target Server Type    : MySQL
     12  Target Server Version : 50624
     13  File Encoding         : utf-8
     14 
     15  Date: 10/21/2016 06:46:46 AM
     16 */
     17 
     18 SET NAMES utf8;
     19 SET FOREIGN_KEY_CHECKS = 0;
     20 
     21 -- ----------------------------
     22 --  Table structure for `class`
     23 -- ----------------------------
     24 DROP TABLE IF EXISTS `class`;
     25 CREATE TABLE `class` (
     26   `cid` int(11) NOT NULL AUTO_INCREMENT,
     27   `caption` varchar(32) NOT NULL,
     28   PRIMARY KEY (`cid`)
     29 ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
     30 
     31 -- ----------------------------
     32 --  Records of `class`
     33 -- ----------------------------
     34 BEGIN;
     35 INSERT INTO `class` VALUES ('1', '三年二班'), ('2', '三年三班'), ('3', '一年二班'), ('4', '二年九班');
     36 COMMIT;
     37 
     38 -- ----------------------------
     39 --  Table structure for `course`
     40 -- ----------------------------
     41 DROP TABLE IF EXISTS `course`;
     42 CREATE TABLE `course` (
     43   `cid` int(11) NOT NULL AUTO_INCREMENT,
     44   `cname` varchar(32) NOT NULL,
     45   `teacher_id` int(11) NOT NULL,
     46   PRIMARY KEY (`cid`),
     47   KEY `fk_course_teacher` (`teacher_id`),
     48   CONSTRAINT `fk_course_teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`tid`)
     49 ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
     50 
     51 -- ----------------------------
     52 --  Records of `course`
     53 -- ----------------------------
     54 BEGIN;
     55 INSERT INTO `course` VALUES ('1', '生物', '1'), ('2', '物理', '2'), ('3', '体育', '3'), ('4', '美术', '2');
     56 COMMIT;
     57 
     58 -- ----------------------------
     59 --  Table structure for `score`
     60 -- ----------------------------
     61 DROP TABLE IF EXISTS `score`;
     62 CREATE TABLE `score` (
     63   `sid` int(11) NOT NULL AUTO_INCREMENT,
     64   `student_id` int(11) NOT NULL,
     65   `course_id` int(11) NOT NULL,
     66   `num` int(11) NOT NULL,
     67   PRIMARY KEY (`sid`),
     68   KEY `fk_score_student` (`student_id`),
     69   KEY `fk_score_course` (`course_id`),
     70   CONSTRAINT `fk_score_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`cid`),
     71   CONSTRAINT `fk_score_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`sid`)
     72 ) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8;
     73 
     74 -- ----------------------------
     75 --  Records of `score`
     76 -- ----------------------------
     77 BEGIN;
     78 INSERT INTO `score` VALUES ('1', '1', '1', '10'), ('2', '1', '2', '9'), ('5', '1', '4', '66'), ('6', '2', '1', '8'), ('8', '2', '3', '68'), ('9', '2', '4', '99'), ('10', '3', '1', '77'), ('11', '3', '2', '66'), ('12', '3', '3', '87'), ('13', '3', '4', '99'), ('14', '4', '1', '79'), ('15', '4', '2', '11'), ('16', '4', '3', '67'), ('17', '4', '4', '100'), ('18', '5', '1', '79'), ('19', '5', '2', '11'), ('20', '5', '3', '67'), ('21', '5', '4', '100'), ('22', '6', '1', '9'), ('23', '6', '2', '100'), ('24', '6', '3', '67'), ('25', '6', '4', '100'), ('26', '7', '1', '9'), ('27', '7', '2', '100'), ('28', '7', '3', '67'), ('29', '7', '4', '88'), ('30', '8', '1', '9'), ('31', '8', '2', '100'), ('32', '8', '3', '67'), ('33', '8', '4', '88'), ('34', '9', '1', '91'), ('35', '9', '2', '88'), ('36', '9', '3', '67'), ('37', '9', '4', '22'), ('38', '10', '1', '90'), ('39', '10', '2', '77'), ('40', '10', '3', '43'), ('41', '10', '4', '87'), ('42', '11', '1', '90'), ('43', '11', '2', '77'), ('44', '11', '3', '43'), ('45', '11', '4', '87'), ('46', '12', '1', '90'), ('47', '12', '2', '77'), ('48', '12', '3', '43'), ('49', '12', '4', '87'), ('52', '13', '3', '87');
     79 COMMIT;
     80 
     81 -- ----------------------------
     82 --  Table structure for `student`
     83 -- ----------------------------
     84 DROP TABLE IF EXISTS `student`;
     85 CREATE TABLE `student` (
     86   `sid` int(11) NOT NULL AUTO_INCREMENT,
     87   `gender` char(1) NOT NULL,
     88   `class_id` int(11) NOT NULL,
     89   `sname` varchar(32) NOT NULL,
     90   PRIMARY KEY (`sid`),
     91   KEY `fk_class` (`class_id`),
     92   CONSTRAINT `fk_class` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`)
     93 ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
     94 
     95 -- ----------------------------
     96 --  Records of `student`
     97 -- ----------------------------
     98 BEGIN;
     99 INSERT INTO `student` VALUES ('1', '', '1', '理解'), ('2', '', '1', '钢蛋'), ('3', '', '1', '张三'), ('4', '', '1', '张一'), ('5', '', '1', '张二'), ('6', '', '1', '张四'), ('7', '', '2', '铁锤'), ('8', '', '2', '李三'), ('9', '', '2', '李一'), ('10', '', '2', '李二'), ('11', '', '2', '李四'), ('12', '', '3', '如花'), ('13', '', '3', '刘三'), ('14', '', '3', '刘一'), ('15', '', '3', '刘二'), ('16', '', '3', '刘四');
    100 COMMIT;
    101 
    102 -- ----------------------------
    103 --  Table structure for `teacher`
    104 -- ----------------------------
    105 DROP TABLE IF EXISTS `teacher`;
    106 CREATE TABLE `teacher` (
    107   `tid` int(11) NOT NULL AUTO_INCREMENT,
    108   `tname` varchar(32) NOT NULL,
    109   PRIMARY KEY (`tid`)
    110 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
    111 
    112 -- ----------------------------
    113 --  Records of `teacher`
    114 -- ----------------------------
    115 BEGIN;
    116 INSERT INTO `teacher` VALUES ('1', '张磊老师'), ('2', '李平老师'), ('3', '刘海燕老师'), ('4', '朱云海老师'), ('5', '李杰老师');
    117 COMMIT;
    118 
    119 SET FOREIGN_KEY_CHECKS = 1;
    View Code
    拷贝上述代码,新建一个.sql文件,保存到桌面
    
    打开navicat新建数据库day41,选中新建的数据库鼠标右键选择运行SQL文件
    
    弹出文件框,选中刚刚保存到桌面的.sql文件即可

    练习题:

     1 1、查询所有的课程的名称以及对应的任课老师姓名
     2 4、查询平均成绩大于八十分的同学的姓名和平均成绩
     3 7、 查询没有报李平老师课的学生姓名
     4 8、 查询没有同时选修物理课程和体育课程的学生姓名
     5 9、 查询挂科超过两门(包括两门)的学生姓名和班级
     6 # 参考答案
     7 #1、查询所有的课程的名称以及对应的任课老师姓名
     8 SELECT
     9     course.cname,
    10     teacher.tname
    11 FROM
    12     course
    13 INNER JOIN teacher ON course.teacher_id = teacher.tid;
    14 #4、查询平均成绩大于八十分的同学的姓名和平均成绩
    15 SELECT
    16     student.sname,
    17     t1.avg_num
    18 FROM
    19     student
    20 INNER JOIN (
    21     SELECT
    22         student_id,
    23         avg(num) AS avg_num
    24     FROM
    25         score
    26     GROUP BY
    27         student_id
    28     HAVING
    29         avg(num) > 80
    30 ) AS t1 ON student.sid = t1.student_id;
    31 #7、 查询没有报李平老师课的学生姓名(找出报名李平老师课程的学生,然后取反就可以)
    32 SELECT
    33     student.sname
    34 FROM
    35     student
    36 WHERE
    37     sid NOT IN (
    38         SELECT DISTINCT
    39             student_id
    40         FROM
    41             score
    42         WHERE
    43             course_id IN (
    44                 SELECT
    45                     course.cid
    46                 FROM
    47                     course
    48                 INNER JOIN teacher ON course.teacher_id = teacher.tid
    49                 WHERE
    50                     teacher.tname = '李平老师'
    51             )
    52     );
    53 #8、 查询没有同时选修物理课程和体育课程的学生姓名(没有同时选修指的是选修了一门的,思路是得到物理+体育课程的学生信息表,然后基于学生分组,统计count(课程)=1)
    54 SELECT
    55     student.sname
    56 FROM
    57     student
    58 WHERE
    59     sid IN (
    60         SELECT
    61             student_id
    62         FROM
    63             score
    64         WHERE
    65             course_id IN (
    66                 SELECT
    67                     cid
    68                 FROM
    69                     course
    70                 WHERE
    71                     cname = '物理'
    72                 OR cname = '体育'
    73             )
    74         GROUP BY
    75             student_id
    76         HAVING
    77             COUNT(course_id) = 1
    78     );
    79 
    80 # 9、 查询挂科超过两门(包括两门)的学生姓名和班级
    81 select student.sname,class.caption from class INNER JOIN student
    82     on class.cid = student.class_id
    83     WHERE student.sid in 
    84     (select student_id from score where num < 60
    85     GROUP BY student_id
    86     HAVING COUNT(course_id) >=2)
    87     ;
    View Code

    二.pymysql模块

    # 模块:pymysql
    import pymysql
    
    
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        password = '123',
        database = 'day38',
        charset = 'utf8'  # 编码千万不要加- 如果写成了utf-8会直接报错
    )
    cursor = conn.cursor(pymysql.cursors.DictCursor)  # 产生一个游标对象  以字典的形式返回查询出来的数据 键是表的字段  值是表的字段对应的信息
    sql = 'select * from teacher'
    cursor.execute(sql)  # 执行传入的sql语句
    # print(res)  # res是执行语句返回的数据条数
    print(cursor.fetchone())  # 只获取一条数据
    print(cursor.fetchone())  # 只获取一条数据
    print(cursor.fetchone())  # 只获取一条数据
    # cursor.scroll(2,'absolute')  # 控制光标移动   absolute相对于其实位置 往后移动几位
    cursor.scroll(1,'relative')  # relative相对于当前位置 往后移动几位
    print(cursor.fetchall())  # 获取所有的数据  返回的结果是一个列表

    三.sql注入 即 增删改查

    import pymysql
    
    
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        password = '123',
        database = 'day38',
        charset = 'utf8',  # 编码千万不要加- 如果写成了utf-8会直接报错
        autocommit = True  # 这个参数配置完成后  增删改操作都不需要在手动加conn.commit了
    )
    cursor = conn.cursor(pymysql.cursors.DictCursor)  # 产生一个游标对象  以字典的形式返回查询出来的数据 键是表的字段  值是表的字段对应的信息
    
    
    
    # sql = 'insert into user(name,password) values("jerry","666")'
    # sql = 'update user set name = "jasonhs" where id = 1'
    sql = 'delete from user where id = 6'
    cursor.execute(sql)
    
    
    """
    增删改操作 都必须加一句
    conn.commit()操作
    """
    # conn.commit()
    # username = input('username>>>:')
    # password = input('password>>>:')
    # sql = "select * from user where name =%s and password = %s"
    # print(sql)
    # res = cursor.execute(sql,(username,password))  # 能够帮你自动过滤特殊符号 避免sql注入的问题
    # # execute 能够自动识别sql语句中的%s 帮你做替换
    # if res:
    #     print(cursor.fetchall())
    # else:
    #     print('用户名或密码错误')
    
    
    """
    sql注入 就是利用注释等具有特殊意义的符号 来完成一些骚操作
    
    后续写sql语句  不要手动拼接关键性的数据
    而是让excute帮你去做拼接
    
    
    
    
    """
  • 相关阅读:
    Spring restful
    LDAP & Implementation
    Restful levels and Hateoas
    事务隔离的级别
    servlet injection analysis
    session and cookie
    write RE validation
    hello2 source analysis
    匿名函数和递归函数
    生成器和迭代器,列表推导式
  • 原文地址:https://www.cnblogs.com/zahngyu/p/11394414.html
Copyright © 2020-2023  润新知