javaWeb数据库学习笔记

javaWeb整体介绍

Web:全球广域网,也称万维网(www),能够通过浏览器访问的网站

javaWeb:是用Java技术来解决相关Web互联网领域的技术栈,也就是用java来开发网站

网页:展现数据,网页不能直接从数据库中获得数据,所以就要靠javaWeb来实现连接

数据库:储存和管理数据

javaWeb程序:逻辑处理

image-20231226093626183

数据库相关概念

数据库

储存数据的仓库,数据是有组织的进行存储,意思就是有规律的,不是瞎堆进去的

英文:DataBase,简称DB

数据库管理系统

管理数据库的大型软件

英文:DBMS

SQL

结构化查询语言

操作关系型数据库的编程语言

定义操作所有关系型数据库的统一标准

MySQL数据模型

关系型数据库

关系型数据库是建立在关系模型基础上的数据库,简单说,关系型数库是由多张能相互连接的二维表组成的数据库

image-20231226213654554

不是表类型的数据库就不是关系型数据库

优点:

1.都是使用表结构,格式一致,易于维护

2.使用通用的SQL语言操作系统,使用方便,可用于复杂查询

SQL简介

对于同一个需求,每一种数据库操作的方式可能会存在一些不一样的地方,称为“方言”

SQL通用语法

1.SQL语句可以单行或多行书写

2.MySQL数据库的SQL语句不区分大小写,关键字建议使用大写

3.注释

单行注释:– 注释内容 (两个横杠)或 #注释内容(MySQL特有)

多行注释:/* 注释 */

以分号结尾

SQL分类

image-20231226224100266

DDL:操作数据库,表等

DML:对表中的数据进行增删改

DQL:对表中的数据进行查询

DCL:对数据库进行权限控制

操作数据库

image-20231226224614339

打开MySQL数据库:mysql -uroot -p

image-20231226225158999

操作表-查询表-创建表

image-20231227084609193

查询表

查询前要进到数据库中,使用use数据库名称语句

image-20231227085028984

查询表结构

image-20231227085147043

image-20231227085310243

tb_user 是表名

id是字段名

数据类型可以是多种的

image-20231227085726174

操作表数据类型

image-20231227092253736

image-20231227092632503

定长的意思是,不管存多少都是10,储存性能高,浪费空间

变长就是实际长度储存性能低,节省空间

image-20231227093115147

image-20231227093308898

操作表删除&修改

image-20231227125912842

image-20231227130226225

操作数据,数据添加,修改,删除

image-20231227214712196

image-20231227222640026

image-20231227223352649

这个where后面的语句可以作为区分与其他语句的不同之处

若没有加where条件,那么所有的数据都会被改变

DQL查询操作

image-20231227224126157

基础查询

image-20231227224250334

image-20231227224714132

条件查询

image-20231228085515857

 select * from new where score >= 60 and score <=100;
 select * from new where age between 20 and 30;
 两种都可以
 select * from new where age = 18;
 //这个里面没有==
 !=还有<>都是不等于号
 select * from new where age in(10,20,30);//三选一
 ​

查询英语成绩为null的学员信息

null不可以直接用=,!=来比较只能用is,不是的话用is not null

 select * from new where english is null;

模糊查询

 1.查询性马的学员
 select * from new where name like '马%';
 2.查询第二个字是马的学员
 select * from new where name like '_马%';
 3.查询名字中包含德的学生信息
 select * from new where name like '德';
 ​

排序查询

升序排序

 
select * from new order by math asc;

降序排序

 
select * from new order by english desc;

两种顺序排序

 select * from new order by math asc,english desc;

当有多个排序时,左边的排序执行完之后,才能执行右边的排序

聚合函数:

1.概念:

将一列数据作为一个整体,进行纵向计算

image-20231228092148190

 1.统计班级有多少人
 select count(*) from new ;
 2.查询数学最高分
 select max(math) from new;
 ​

当有null时不参与排序

分组查询

image-20231228093259119

 1.查询男女同学的数学平均成绩
 select sex, avg(math),from new group by sex;
 2.查询男女同学数学平均分成绩及人数
 select sex, avg(math),count(*),from new group by sex;
 3.查询~低于70不参与分组
 select sex,avg(math),count(*),from new where score > 70 group by sex;
 4.查询~分组之后人数大于2
 select sex,avr(math),count(*),from new where score > 70
 group by sex having count(*) > 2;
 ​

分页查询

image-20231228094443426

 
每页显示三条数据,查询第二页
 select * from new limit 3 , 3;
 ​

约束

约束的概念和分类

1.约束是作用于表中列上的规则,就是对数据及及进行规范

约束是为了保证数据的正确性与准确性

2.约束的分类

非空约束:保证数值不可以为null 关键字 NOT NULL

唯一约束:保证数据不重复 关键字 UNIQUE

主键约束:是一行数据的为一标识,要求非空且唯一 关键字 PRIMARY FEY

检查约束:保证列中的值满足某一条件 关键字 CHECK

比如说让数值在某一范围

默认约束:保存数值时,未指定值,则采用默认值 关键字 DEFAULT

外键约束:让两个表的数值之间建立链接,保证数值的一致性和完整性

关键字 FOREIGN KEY

MySQL不接受检查约束

约束演示

自动增长

auto_increment当列是数字的时候从小到大依次增长

 DROP TABLE IF EXISTS new1;
 CREATE TABLE new1 (
     id INT PRIMARY KEY auto_increment,
     ename VARCHAR(50) NOT NULL UNIQUE ,
     birthday DATE NOT NULL,
     salary DOUBLE(7,2) NOT NULL,
     bonus DOUBLE(7,2) DEFAULT 0
 );
 ​
 SELECT * FROM new1;
 INSERT INTO new1 (id,ename,birthday,salary,bonus) VALUES (1,'李宇航','2004-11-15',10000,5000);
 INSERT INTO new1 (id,ename,birthday,salary,bonus) VALUES (3,'张梓豪','2004-11-16',9000,4000);
 INSERT INTO new1 (id,ename,birthday,salary,bonus) VALUES (2,'王明杰','2004-11-17',8000,3000);

外键约束

image-20240108174307743

image-20240108213706575

除了外键约束之外,主表和附表之间若是要有联系,那么不光数据类型要一致,其余约束条件也要一致,除此之外,主表关联的数目也要大于等于附表,否则在添加数据时,就会添加不进去,还有创建表的时候要先创建主表,再创建附表,添加数据时也要先添加主表数据,再添加副标数据

image-20240108214146067

image-20240108214205898

 DROP table IF EXISTS new2;
 CREATE TABLE new2(
     id2 INT PRIMARY KEY auto_increment,
     group1 VARCHAR(50)
     ); 
     SELECT * FROM new2;
 INSERT INTO new2(id2,group1) VALUES(1,'第一组');
 INSERT INTO new2(id2,group1) VALUES(2,'第二组');
 INSERT INTO new2(id2,group1) VALUES(3,'第三组');
 ​
 DROP TABLE IF EXISTS new1;
 ​
 SELECT * FROM new1;
 ​
 CREATE TABLE new1 (
 id INT PRIMARY KEY auto_increment,
 ename VARCHAR(50) NOT NULL UNIQUE,
 birthday DATE NOT NULL,
 salary DOUBLE(7,2) NOT NULL,
 bonus DOUBLE(7,2) DEFAULT 0 ,
     CONSTRAINT fk_new1_new2 FOREIGN KEY (id) REFERENCES new2(id2)
     );
     INSERT INTO new1 (id,ename,birthday,salary,bonus) VALUES (1,'李宇航','2004-11-15',10000,5000);
 INSERT INTO new1 (id,ename,birthday,salary,bonus) VALUES (2,'张梓豪','2004-11-16',9000,4000);
 INSERT INTO new1 (id,ename,birthday,salary,bonus) VALUES (3,'王明杰','2004-11-17',8000,3000);
 --在外部添加
     --断开连接
     ALTER TABLE new1 DROP FOREIGN KEY fk_new1_new2;
     --添加链接
     ALTER TABLE new1 ADD CONSTRAINT fk_new1_new2 FOREIGN KEY(id) REFERENCES new2(id2);

数据库设计

数据库设计简介

image-20240108221036808

数据库多表实现关系

在多对多时要想实现联系,那么就要借助于第三张表

 DROP table IF EXISTS biao1;
 CREATE TABLE biao1(
         index1 INT,
         eNAME VARCHAR(50) NOT NULL UNIQUE,
         biao1_index INT PRIMARY KEY auto_increment
 ); 
 SELECT * FROM biao1;
 ​
 DROP table IF EXISTS biao2;
 CREATE TABLE biao2(
         index2 int,
         NAME VARCHAR(50) NOT NULL UNIQUE,
         biao2_index INT PRIMARY KEY auto_increment
 );
 SELECT * FROM biao2;
 DROP table IF EXISTS biao3;
 CREATE TABLE biao3(
         index3 int PRIMARY KEY auto_increment,
         biao3_index1 int ,
         biao3_index2 INT
 );
 ​
 SELECT * FROM biao3;
 alter table biao3 add CONSTRAINT fk_biao3_index1 FOREIGN KEY (biao3_index1) REFERENCES biao1(biao1_index);
 alter table biao3 add CONSTRAINT fk_biao3_index2 FOREIGN KEY (biao3_index2) REFERENCES biao2(biao2_index);

不知道为什么只有带约束才能被关联

多表查询

简介

笛卡尔积:两个集合的所有情况会同时出现

解决办法:消除无效数据,添加条件

内连接:相当于两个表的交集,

外连接分为左外连接还有右外连接,左外连接就是左边表的全部信息还有交集部分,右外连接就是右边表还有交际部分

子查询:

内连接还有外连接

隐式内连接

 SELECT * FROM new1,new2 WHERE new1.id = new2.id2;


 SELECT
     new1.ename,
     new1.birthday 
 FROM
     new1,
     new2 
 WHERE
     new1.id = new2.id2;

显式内连接

 SELECT * FROM new1 INNER JOIN new2 ON new1.id = new2.id2;

inner可以省略

左外连接

 
SELECT * FROM NEW1 LEFT JOIN NEW2 ON NEW.ID = NEW2.ID2;
 ​

右外连接

 SELECT * FROM NEW2 RIGHT JOIN NEW1 ON NEW.ID = NEW2.ID2;

子查询

查询中嵌套查询就是子查询,里面看作是查询的一个条件

单行单列查询,多行单列查询,多行多列查询

单行单列

 SELECT eNAME , birthday FROM new1 WHERE salary >(SELECT salary FROM new1 WHERE ename = '');
多行单列

 SELECT eNAME ,BRITHDAY FROM NEW1 WHERE ID IN (SELECT ID FROM NEW2 WHERE ID2 = 1 OR ID2 = 2);
多行多列

     SELECT * from (select * from new1 WHERE id = 1 or id =2 ) biao4 WHERE biao4.eNAME = '';

事务

事务简介

事务是一种机制,一个操作序列,包含了一组数据库操作命令

事务·把所有命令作为一个整体一起向系统提交或撤销操作请求,这一组指令要么同时成功要么同时失败,

事务是一个不可分割的工作逻辑单元

由三部分:开启事务,回滚事务,提交事务

开启事务时造成的是临时更改,只有提交事务之后才能真正在数据库修改数据,只是自己的页面可以看到更改,其他页面不会更改

    
 BEGIN;
     UPDATE new1 SET salary = salary - 500 WHERE ename = '';
     ROLLBACK;
     COMMIT;

image-20240109170707805

不以事务格式执行的话就是永久更改

JDBC

JDBC简介

在idea里面对数据库内容进行更改

是sun公司定义的一套操作所有关系型数据库的规则,即接口

各个数据库提供jar包

真正执行的代码是驱动jar包中的实现类

优点:可以通过这个对所有数据库进行操作

可以随时替换底层数据库,访问的java代码不改变

入门

 public class qwwe {
     public static void main(String[] args) throws Exception {
         //1.注册驱动
         Class.forName("com.mysql.jdbc.Driver");
         //上面这个写不写都行,因为驱动包里面就已经带着有了
         //2.获取连接
         String url = "jdbc:mysql://127.0.0.1:3306/db1";
         String username = "root";
         String password = "1040272215Aa";
 ​
         Connection connection = DriverManager.getConnection(url,username,password);
 ​
 ​
         //3.定义sql
         String sql = "update new1 set salary = 10000 where id = 2 ";
 ​
         //4.获取sql的对象Statement
         Statement statement = connection.createStatement();
 ​
         //5.执行sql
         int count = statement.executeUpdate(sql);
 ​
         //6.处理结果
         System.out.println(count);
 ​
         //7.释放资源
         statement.close();
         connection.close();
     }
 }

DriverManager

是个工具类

1.注册驱动

 
  Class.forName("com.mysql.jdbc.Driver");

2.获取数据库连接

 DriverManager.getConnection(url,username,password);

image-20240110150833478

端口号,还有ip可以省略,数据库想使用哪个就用哪个数据库,是数据库,不是表

 String url = "jdbc:mysql:///db1";

Connection

1.获取执行SQL的对象

image-20240110151721625

2.管理事务

 //开启事务
 setAutoCommit(boolean autoCommit): true为自动提交事务,false为手动提交事务

Statement

作用

1.执行SQL语句

 int count1 = statement.executeUpdate(sql1);
 int count2 = statement.executeUpdate(sql2);

image-20240110154449935

ResultSet

获取查询数据

next方法 返回boolean类型数据

将光标从当前位置向下移动一行,并判断当前行是否为有效行

true:有效行,当前行有数据

false:无效行,当前行没有数据

获取数据

get xxx(参数)参数:列的编号 还有列的名称

getint放回int类型数据

 public class qwwe {
     public static void main(String[] args) throws Exception {
         ArrayList<bao> arrayList = new ArrayList<>();
         //1.注册驱动
         //Class.forName("com.mysql.jdbc.Driver");
         //2.获取连接
         String url = "jdbc:mysql://127.0.0.1:3306/db1";
         String username = "root";
         String password = "1040272215Aa";
 ​
         Connection connection = DriverManager.getConnection(url,username,password);
         String sql = "select * from new1";
         Statement statement = connection.createStatement();
         ResultSet resultSet =  statement.executeQuery(sql);
         while(resultSet.next()){
             bao bao1 = new bao();
             String string = resultSet.getString(2);
             bao1.setName(string);
             arrayList.add(bao1);
         }
         System.out.println(arrayList);
 ​
         //7.释放资源
         resultSet.close();
         statement.close();
         connection.close();
     }
 }

PrepareStatement

1.作用:与编译SQL语句并执行,预防SQL注入问题,将敏感字符进行转义

SQL注入

修改SQL语句,用以达到对服务器进行攻击的方法

image-20240110173316263

 public class qwwe {
     public static void main(String[] args) throws Exception {
 ​
         //1.注册驱动
         //Class.forName("com.mysql.jdbc.Driver");
         //2.获取连接
         String url = "jdbc:mysql://127.0.0.1:3306/db1";
         String username = "root";
         String password = "1040272215Aa";
 ​
         Connection connection = DriverManager.getConnection(url,username,password);
         Scanner scanner = new Scanner(System.in);
         String name = scanner.next();
         String birthday = scanner.next();
 ​
         String sql = "select * from new1 where ename = ? and birthday = ?";
         PreparedStatement pstmt = connection.prepareStatement(sql);
         pstmt.setString(1,name);
         pstmt.setString(2,birthday);
         ResultSet resultSet =pstmt.executeQuery();
        if(resultSet.next()){
            System.out.println("登陆成功");
 ​
        }else{
            System.out.println("登陆失败");
        }
 ​
         //7.释放资源
         resultSet.close();
         pstmt.close();
         connection.close();
     }
 }

原理:

image-20240111102943741

 String url = "jdbc:mysql:///db1?useServerPrepStmts = true";

数据库连接池

简介

是个容器,负责分配,管理数据库连接,如果没有连接池,就会来一个人建立一个连接,之后就会关闭

释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏

好处:

资源重新用

提升系统影响速度

避免数据库连接遗漏,就是怕有的用户没有连接可用

image-20240111104503610

image-20240111104731551

Druid

 //driverClassName = com.mysql.jdbc.Driver
 url = jdbc:mysql:///db1?useSSL = false& useServerPreStmts = true
 password = 1040272215Aa
 username = root
 #初始化连接数量
 initialSize = 5
 #最大连接数量
 maxAction = 10
 #最大等待时间
 maxWait = 3000

 public class test {
     public static  void main(String[] args) throws Exception {
         //加载配置文件
         Properties properties = new Properties();
         properties.load(new FileInputStream("src/druid.properties"));
         //获取连接池对象
         DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
         //获取链接
         Connection connection = dataSource.getConnection();
         System.out.println(connection);
 ​
     }
 }

查询功能

实体类中,基本数据类型选为包装类

 public class Main {
     public static void main(String[] args) throws Exception {
         ArrayList<test> list = new ArrayList<>();
         //加载配置文件
         Properties properties = new Properties();
         properties.load(new FileInputStream("src/druid.properties"));
         //获取连接池对象
         DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
         //获取链接
         Connection connection = dataSource.getConnection();
 ​
         String sql = "select * from brand";
         PreparedStatement pstmt = connection.prepareStatement(sql);
         ResultSet resultSet = pstmt.executeQuery();
         test test1 = new test();
         while(resultSet.next()){
             int id = resultSet.getInt("id");
             String brand = resultSet.getString("brand");
             String company = resultSet.getString("company");
             int ordered = resultSet.getInt("ordered");
             String description = resultSet.getString("description");
             int status1 = resultSet.getInt("status1");
             test1.setId(id);
             test1.setBrand(brand);
             test1.setCompany(company);
             test1.setOrdered(ordered);
             test1.setDescription(description);
             test1.setStatus1(status1);
             list.add(test1);
 ​
         }
         System.out.println(list);
         resultSet.close();
         pstmt.close();
         connection.close();
     }
 }

数据库添加

 
public class Main {
     public static void main(String[] args) throws Exception {
         Scanner scanner = new Scanner(System.in);
         String brand = scanner.next();
         String company = scanner.next();
         int ordered = scanner.nextInt();
         String description = scanner.next();
         int status1  = scanner.nextInt();
         //加载配置文件
         Properties properties = new Properties();
         properties.load(new FileInputStream("src/druid.properties"));
         //获取连接池对象
         DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
         //获取链接
         Connection connection = dataSource.getConnection();
 ​
         String sql = "insert into brand (brand,company,ordered,description,status1)values (?,?,?,?,?)";
         PreparedStatement pstmt = connection.prepareStatement(sql);
         pstmt.setString(1,brand);
         pstmt.setString(2,company);
         pstmt.setInt(3,ordered);
         pstmt.setString(4,description);
         pstmt.setInt(5,status1);
         int i = pstmt.executeUpdate();
         System.out.println(i >0);
 ​
 ​
         pstmt.close();
         connection.close();
     }
 }

image-20240111162743241

数据库修改

 public class Main {
     public static void main(String[] args) throws Exception {
         Scanner scanner = new Scanner(System.in);
         String description = scanner.next();
         int id = scanner.nextInt();
         //加载配置文件
         Properties properties = new Properties();
         properties.load(new FileInputStream("src/druid.properties"));
         //获取连接池对象
         DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
         //获取链接
         Connection connection = dataSource.getConnection();
         String sql = "update brand set description = ? where id = ?";
         PreparedStatement pstmt = connection.prepareStatement(sql);
         pstmt.setString(1,description);
         pstmt.setInt(2,id);
         int i = pstmt.executeUpdate();
         System.out.println(i >0);
         pstmt.close();
         connection.close();
     }
 }

数据库数据删除

 public class Main {
     public static void main(String[] args) throws Exception {
         Scanner scanner = new Scanner(System.in);
    
         int id = scanner.nextInt();
         //加载配置文件
         Properties properties = new Properties();
         properties.load(new FileInputStream("src/druid.properties"));
         //获取连接池对象
         DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
         //获取链接
         Connection connection = dataSource.getConnection();
 ​
         String sql = "delete from brand where id = ?";
         PreparedStatement pstmt = connection.prepareStatement(sql);
       
         pstmt.setInt(1,id);
         int i = pstmt.executeUpdate();
         System.out.println(i >0);
 ​
 ​
         pstmt.close();
         connection.close();
     }
 }

  • 15
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰哥的狗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值