JavaWeb Study Notes 01 - Database

JavaWeb is composed of database, front end and web core, first learn the first part of database

1. MySQL

1.1 Login

登录参数: mysql -u用户名 -p密码 -h要连接的mysql服务器的ip地址(默认127.0.0.1) -P端口号(默认3306)

1.2 MySQL data model

Relational database: A database based on a relational model, consisting of multiple two-dimensional tables that can be connected to each other . Simply put, it is a database that stores data through tables

2. SQL

2.1 General syntax

  1. SQL statements can be written in one or more lines, ending with a semicolon
  2. MySQL SQL statements are not case sensitive
  3. Notes:
    • Single-line comment: -- comment content ( must have spaces ) or # comment content (MySQL specific)
    • Multi-line comment: /* comment */

2.2 Language Classification

DDL

Data Definition Language: Manipulating Databases and Tables

1. Operate the database

Inquire

SHOW DATABASE;

create

  • create database
    CREATE DATABASE 数据库名称;
    
  • Create a database (judgment, if it does not exist, it will not be created)
    CREATE DATABASE IF NOT EXISTS 数据库名称;
    

delete

  • delete database
    DROP DATABASE 数据库名称;
    
  • Delete the database (judgment, delete if it exists)
    DROP DATABASE IF EXISTS 数据库名称;
    

use

  • View the currently used database
    SELECT DATABASE();
    
  • use database
    USE 数据库名称;
    

2. Operation table

Operation Syntax
Query

  • Query all table names
    SHOW TABLES;
    
  • query table structure
    DESC 表名称;
    

create

create table tb_user(
   id int,
   username varchar(20), -- 表示不能超过20位
   password varchar(32)  -- 此处不能有逗号
);

Note: Do not add a comma at the end of the last line

Delete
is the same as deleting a database

Revise

  • modify table name
    ALTER TABLE 表名 RENAME TO 新的表名;
    
  • add a column
    ALTER TABLE 表名 ADD 列名 数据类型;
    
  • modify data type
    ALTER TABLE 表名 MODIFY 列名 新的数据类型;
    
  • Modify column names and data types
    ALTER TABLE 表名 CHANGE 列名 新列名 新数据类型;
    
  • delete column
    ALTER TABLE 表名 DROP 列名;
    

type of data
insert image description here

DML

Data manipulation language: adding, deleting, and modifying data in tables

1. Add data

Add data to the specified column

INSERT INTO 表名(列名1,列名2...) VALUES(1,2...);
#INSERT INTO stu(id,name) VALUES(1,'张三');

Add data to all columns

INSERT INTO 表名 VALUES(1,2...);
#INSERT INTO stu VALUES(2,'李四','男','1999-11-11','88.88','[email protected]','13888888888','1');

Add data in batches

INSERT INTO 表名 (列名1,列名2...) VALUES(1,2...),(1,2...),(1,2...)...;
INSERT INTO 表名 VALUES(1,2...),(1,2...),(1,2...)...;

2. Modify data

UPDATE 表名 SET 列名1=1,列名2=2,...WHERE 条件; -- 如果不加条件则修改所有数据
#UPDATE stu SET gender='女',birthday='1999-12-12',score=99.99 where name = '张三';

3. Delete data

DELETE FROM 表名 WHERE 条件; -- 如果不加条件则删除所有数据
#DELETE FROM stu where name = '张三';

DQL

Data query language: query the data in the table ( the most important )
query syntax

SELECT    字段列表
FROM      表名列表
WHERE     条件列表
GROUP BY  分组字段
HAVING    分组后条件
ORDER BY  排序字段
LIMIT     分页限定

0. Aggregate function

select 聚合函数名(列名) from 表名;
# select count(*) from stu; //计算数量列名推荐使用*

insert image description here
Note: null values ​​do not participate in all aggregate function operations

1. Basic query

Query multiple fields

SELECT 字段列表 FROM 表名;
SELECT * FROM 表名;   --查询所有数据

Remove duplicate records

SELECT DISTINCT 字段列表 FROM 表名;

alias

SELECT name,math as 数学成绩 ,english as 英语成绩 from stu; -- as也可以省略

insert image description here

2. Condition query

SELECT 字段列表 FROM 表名 WHERE 条件列表;
# select * from stu where hire_date between '1998-9-1' and '1999-9-1'; 
# select * from stu where english = null; -- 报错
-- 模糊查询
# select * from stu where name like '马%';  -- 姓马
# select * from stu where name like '_花%'; -- 第二字为花
# select * from stu where name like '%德%'  -- 名字中含有德

insert image description here
Note: = / = cannot be used for comparison of nul values, you need to use is / is not

3. Sort query

sort by:

  • ASC: ascending order (default)
  • DESC: Sort in descending order
select 字段列表 FROM 表名 ORDER BY 排序字段名1 排序方式1, 排序字段名2 排序方式2...;
# select * from stu order by age asc;
# select * from stu order by math desc, english asc; -- 数学成绩相同,则按英语成绩降序

When there are multiple sorting conditions, only when the value of the previous condition is the same, it will be sorted according to the latter condition

4. Group query

select 字段列表 FROM 表名 GROUP BY 分组字段名 having 分组后条件过滤;
# select sex,avg(math) from stu group by sex;  -- 查询男女同学最高分
# select sex,count(*) ,avg(math) from stu group by sex; -- 查询男女同学人数和最高分
# select sex,count(*) ,avg(math) from stu where math > 70 group by sex;-- 查询男女同学人数和最高分(分数低于70的不参与分组)
# select sex,count(*) ,avg(math) from stu where math > 70 group by sex having count(*) > 2; -- 查询男女同学人数和最高分(分数低于70的不参与分组),且组内人数大于两个

- After grouping, the fields to be queried are aggregation functions and grouping fields, and it is meaningless to query other fields

- Execution order: WHERE > aggregate function > HAVING

- The difference between WHERE and HAVING:

  • WHERE is limited before grouping, if the condition is not met, grouping will not be performed, and HAVING is to filter the results after grouping
  • WHERE cannot judge aggregate functions, HAVING can

5. Paging query

select 字段列表 from 表名 limit 起始索引 , 查询条目数;
# select * from stu limit 0,3; -- limit起始索引从0开始
# select * from stu limit 3,3; -- limit = (当前页码-1)*条目数
# select * from stu limit 6,3;

Start index limit = (current page number - 1) * number of items displayed on each page

Paging query limit is the dialect of MySQL, Oracle uses rownumbe, and SQL Server uses top

DCL

Data control language: control the authority of the database
*This content is not currently used, so don't learn

2.3 Constraints

  • Constraints are rules that act on columns in a table to limit the data that is added to the table
  • Constraints ensure the correctness, validity, and integrity of data in the database

Constraint Classification

  • NOT NULL constraint
  • Unique constraint UNIQUE
  • Primary key constraint PRIMARY KEY
  • Check constraints CHECK (not supported by MySQL)
  • default constraint DEFAULT
  • Foreign key constraint FOREIGN KEY

Add constraints before creating the table

CREATE TABLE emp (
	# auto_increment:自动增长 当列是数字类型 且 唯一约束
	id INT PRIMARY KEY auto_increment,  #主键:非空且唯一
	ename VARCHAR(50) NOT NULL UNIQUE,
	joindate DATE NOT NULL,
	salary DOUBLE(7,2) NOT NULL,
	bonus DOUBLE(7,2) DEFAULT 0
);

foreign key constraint
creation

  • Add constraints before creating the table
    create table emp(
    	#表的内容
    	CONSTRAINT 外键名称 FOREIGN KEY(外键列名) REFERENCES 主表(主表列名)
    );
    
  • Add constraints after table creation
    ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY(外键列名) REFERENCES 主表(主表列名)
    

delete

ALTER TABLE emp DROP FOREIGN KEY fk_emp_dept;

Note:
(1) Create the master table first, and then create the slave table; add the master table data first, and then add the slave table information
(2) The naming method of the foreign key name: fk_slave table name_master table name

3. Database design

3.1 One-on-one

For example: user and user details. It is mostly used for table splitting, put frequently used fields in one table, and infrequently used fields in another table to improve query performance
Implementation method
Add a foreign key to either party, associate the other party's primary key, and set the foreign key as Unique (UNIQUE)

3.2 One-to-many (many-to-one)

Such as: department table and employee table, one part corresponds to multiple employees, and each employee corresponds to one department
Implementation method: establish a foreign key on the multi-party, and point to the primary key on the one-party

-- 部门表
create table dept(
	id int primary key auto_increment,
	dep_name varchar(20),
	addr varchar(20)
);

-- 员工表
create table emp(
	id int primary key auto_increment,
	name varchar(20),
	age int,
	dep_id int,
	CONSTRAINT fk_emp_dept FOREIGN KEY(dep_id) REFERENCES dept(id)
);

insert image description here

3.3 Many-to-many

Such as: product table and order table, one product corresponds to multiple orders, and one order contains multiple products
Realization method: create a third intermediate table, the intermediate table contains at least two foreign keys, and associates the two primary keys respectively

-- 订单表
create table tb_order (

	id int primary key auto_increment,
	payment double(10,2),
	payment_type tinyint,
	status tinyint
);

-- 商品表
create table tb_goods (

	id int primary key auto_increment,
	title varchar(100),
	price double(10,2)

);

-- 中间表
create table tb_order_goods (
	id int primary key auto_increment,
	order_id int ,
	goods_id int ,
	count int
);

-- 添加外键
alter table tb_order_goods add constraint fk_order_id foreign key (order_id) references tb_order(id);
alter table tb_order_goods add constraint fk_goods_id foreign key (goods_id) references tb_goods(id);

insert image description here

4. Multi-table query

4.1 Connection query

Inner join: equivalent to querying the intersection of A and B.
Implicit inner join

SELECT 字段列表 	FROM1,2... WHERE 条件;
# select emp.name,emp.gender,dept.dname from emp,dept where emp.dep_id = dept.did;

Show Inner Links

SELECT 字段列表 	FROM1 INNER JOIN2 ON 条件;
# select * from emp inner join dept on emp.dep_id = dept.did;

Outer join:
left outer join: equivalent to querying all the data in table A and the data in the intersection part

SELECT 字段列表 	FROM1 LEFT OUTER JOIN2 ON 条件;
# select * from emp left outer join dept on emp.dep_id = dept.did;

Right outer join: equivalent to querying all data in table B and the data in the intersection part

SELECT 字段列表 	FROM1 RIGHT OUTER JOIN2 ON 条件;
# select * from emp right outer join dept on emp.dep_id = dept.did;

4.2 Subqueries

A nested query in a query is called a subquery with
a single row and a single column : as a conditional value, use = != > < etc. for conditional judgment

SELECT 字段列表 FROMWHERE 字段名 = (子查询);
# select * from emp where salary > (select emp.salary from emp where name = '猪八戒');

Multi-line single column : as a conditional value, use keywords such as in for conditional judgment

SELECT 字段列表 FROMWHERE 字段名 IN (子查询);
# select * from emp where dep_id in (select did from dept where dname = '财务部' or dname = '市场部');

Multiple rows and multiple columns : as a virtual table

SELECT 字段列表 FROM (子查询) WHERE 条件;
# select * from (select * from emp where join_date > '2011-11-11') t1 ,dept t2 where t1.dep_id = t2.did;

5. Affairs

5.1 Introduction to Transactions

  • Transaction is a mechanism, a sequence of operations, including a set of database operation commands
  • The transaction submits or revokes the operation request to the system together with all commands as a whole, that is, this group of database commands
    either succeeds at the same time or fails at the same time
  • A transaction is an indivisible logical unit of work
-- 开启事务
START TRANSACTION  # 或者 BEGIN
-- 提交事务
COMMIT;
-- 回滚事务
ROLLBACK;

-- 转账操作示例

BEGIN;  -- 开启事务

update account set money = money - 500 where name = '李四';
update account set money = money + 500 where name = '张三';

COMMIT;  -- 提交事务

ROLLBACK; -- 回滚事务

5.2 Four characteristics of transactions (ACID)

  • Atomicity : A transaction is an indivisible smallest unit that either succeeds or fails at the same time
  • Consistency : When the transaction is completed, all data must be kept in a consistent state
  • Isolation : Visibility of operations between multiple transactions
  • Durability : Once a transaction is committed or rolled back, its changes to the data in the database are permanent

5.3 The default submission method of the transaction

MySQL automatically commits by default
Check

select @@autocommit;

If the running result is 1, it means automatic submission by default, and if it is 0, it means manual submission

Revise

set @@autocommit = 0;

Guess you like

Origin blog.csdn.net/m0_62721576/article/details/128448175