Basic concepts of database and MySQL basic operation commands and advanced database operations

Basic concepts of database and MySQL basic operation commands and advanced database operations

One, the basic concept of the database

1. The composition of the database

  • Data: Symbol records describing things,
    including numbers, words, graphics, images, sounds, file records, etc.,
    are stored in a unified format in the form of "records"
  • Table: Organize different records together to store specific data
  • Database: A collection of tables, a warehouse
    for storing data, a collection of related data stored in a certain organizational manner

Database -> Data Table -> Row (Record): Information column (field) used to describe an object: Used to describe an attribute of the object


2. Database management system (DBMS)

It is a system software that realizes effective organization, management and access to database resources.
Functions: database establishment and maintenance functions, data definition functions, data manipulation functions, database operation management functions, and communication functions


3. Database System (DBS)

It is a man-machine system consisting of hardware, OS, database, DBMS, application software and database users

Users can operate the database through DBMS or applications


2. Today's mainstream databases

1. SQL Server (product of Microsoft Corporation)

  • For Windows operating system
  • Simple and easy to use

2. Oracle (A product of Oracle Corporation)

  • For all major platforms
  • Safe, perfect, complicated operation

3. DB2 (product of IBM)

  • For all major platforms
  • Large, safe and complete

4. MySQL (acquired by Oracle)

  • Free, open source, small size

3. Introduction to relational database

1. Relational database system is a database system based on relational model

2. The data structure of the relational model uses a simple and easy-to-understand two-dimensional data table

  • Each line is called a record, used to describe the information of an object
  • Each row is called a field, used to describe an attribute of the object

3. The relational model can be represented by a simple "entity-relation-attribute"

1) Entity

  • Also called an instance, it corresponds to "events" or "things" that can be distinguished from other objects in the real world,
    such as bank customers, bank accounts, etc.

2) Relationship

  • The corresponding relationship between the entity sets is called a connection, also called a relationship. For
    example, there is a "savings" relationship between a bank customer and a bank account.

3) Properties

  • A certain characteristic of an entity, an entity can have multiple attributes. For
    example, each entity in the "bank customer" entity set has attributes such as name, address, and phone number.

Fourth, the introduction of non-relational databases

Non-relational databases are also known as NoSQL (Not Only SQL)

  • The stored data is not based on the relational model and does not require a fixed table format

Advantages of non-relational databases

  • Database can be read and written with high concurrency
  • Efficient storage and access to massive data
  • Database has high scalability and high availability

Five, MySQL database introduction

A popular open source relational database
product owned by Oracle. It
complies with the GPL agreement and can be used and modified for free.
Features

  • Excellent performance and stable service
  • Open source, no copyright restrictions, low cost
  • Multi-threaded, multi-user
  • Based on C/S (client/server) architecture
  • Safe and reliable

Six, MySQL database basic command operation

1. Commonly used data types

Commonly used data types effect
int Integer
float Single-precision floating point-------4 bytes 32-bit
double Double-precision floating point-------8 bytes 64-bit
char Fixed-length character type
varchar Variable length character type
text text
image image
decimal (5,2) 5 effective length numbers with 2 digits after the decimal point

among them:

Char can store up to 255 characters. If the actual length of the data stored in char is less than the specified length, spaces will be added to the specified length; if the actual length of the stored data is greater than the specified length, the lower version will be intercepted, high The version will report an error.
The length of char is immutable, while the length of varchar is variable, that is to say, define a char[10] and varchar[10], if it is stored in'csdn', then the length occupied by char is still 10. In addition to the character'csdn', it is followed by six spaces, and varchar immediately changes the length to 4

Varchar storage rules:
Below version 4.0, varchar(20) refers to 20 bytes. When storing UTF8 Chinese characters, only 6 (3 bytes per Chinese character) can be stored
above version 5.0, varchar(20) refers to It is 20 characters, no matter whether it is stored in numbers, letters or UTF8 Chinese characters (each Chinese character is 3 bytes), it can store 20, and the maximum size is 65532 bytes.

Seven, view the database structure

1. Enter the database before using the command

mysql -u root -p

Insert picture description here

2. View the database in the current server

SHOW DATABASES;						#大小写不区分,分号“;”表示结束

Insert picture description here

3. View the tables contained in the database

USE 数据库名;
SHOW TABLES;

Insert picture description here

3. View the structure of the table (fields)

USE 数据库名;
DESCRIBE [数据库名.]表名;
可缩写成:DESC 表名;

Insert picture description here

4. SQL statement

SQL语句用于维护管理数据库,包括数据查询、数据更新、访问控制、对象管理等功能。

SQL语言分类:
DDL:数据定义语言,用于创建数据库对象,如库、表、索引等
DML:数据操纵语言,用于对表中的数据进行管理
DQL:数据查询语言,用于从数据表中查找符合条件的数据记录.
DCL:数据控制语言,用于设置或者更改数据库用户或角色权限

5. Create and delete databases and tables

1.创建新的数据库
CREATE DATABASE 数据库名;

2.创建新的表
CREATE TABLE 表名 (字段1 数据类型,字段2 数据类型 [,...] [,PRIMARY KEY (主键名)]);
#主键一般选择能代表唯一性的字段 不允许取空值(NULL),一个表只能有一个主键。

例:
CREATE DATABASE school; .
USE school;
CREATE TABLE CLASS01 (id int NOT NULL,name char(10) NOT NULL,score decimal(5,2),passwd char(48)   DEFAULT '',PRIMARY KEY (id)) ;

DESC CLASS01;

3.删除指定的数据表
DROP TABLE [数据库名.] 表名;      #如不用USE进入库中,则需加上数据库名

4.删除指定的数据库
DROP DATABASE 数据库名;

6. Data records in the management table

1.向数据表中插入新的数据记录
INSERT INTO 表名(字段1,字段2[,...]) VALUES(字段1的值,字段2的值, ...);

例:
INSERT INTO CLASS01 (id,name,score,passwd) values (1,'zhangsan',70.5,PASSWORD('123456'));
#PASSWORD('123456'):查询数据记录时,密码字串以加密形式显示;若不使用PASSWORD(),查询时以明文显示。

INSERT INTO CLASS01 VALUES(2,'lisi',90.5,654321);

SELECT * FROM CLASS01;     #查询表的全部数据记录

2.查询数据记录
SELECT 字段名1,字段名2[,...] FROM 表名 [WHERE 条件表达式];

例:
SELECT * FROM CLASS01;
SELECT id,name,score FROM CLASS01 WHERE id=2;

select name from CLASS01\G         #以列表方式竖向显示
select * from CLASS01 limit 2;     #只显示头2行
select * from CLASS01 limit 2,3;   #显示第2行后的前3行

3.修改、更新数据表中的数据记录
UPDATE 表名 SET 字段名1=字段值1[,字段名2=字段值2] [WHERE 条件表达式];

例:
UPDATE CLASS01 SET passwd=PASSWORD('') WHERE name='zhangsan';
UPDATE CLASS01 SET name='wangxiaoer',passwd='' WHERE id=3;

4.在数据表中删除指定的数据记录
DELETE FROM 表名 [WHERE 条件表达式];

例:
DELETE FROM CLASS01 WHERE id=4;
SELECT * FROM CLASS01;

7. Modify the table name and table structure

1.表名修改
ALTER TABLE 旧表名 RENAME 新表名;

例:alter table CLASS01 rename CLASS02;
show tables;
select * from CLASS02;

2.扩展表结构(增加字段)
ALTER TABLE 表名 ADD address varchar(50) default '地址不详';
#default '地址不详':表示此字段设置默认值地址不详;可与NOT NULL配合使用

3.修改字段(列)名,添加唯一键
ALTER TABLE 表名 CHANGE 旧列名 新列名 数据类型 [unique key];

例:
ALTER TABLE CLASS01 CHANGE name user_name varchar(10) unique key;
#CHANGE可修改字段名、数据类型、约束等所有项。

4.删除字段
ALTER TABLE 表名 DROP 字段名;

例:
ALTER TABLE CLASS01 DROP passwd

For example:

use school;
create table if not exists info (
id int(4) zerofill primary key auto_increment,      #指定主键的第二种方式
name varchar(10) not null,
cardid int(18) not null unique key,
hobby varchar(50));

-----------------------------------------------------------------------------------------------
#if not exists: 表示检测要创建的表是否已存在,如果不存在就继续创建
#int(4) zerofill: 表示若数值不满4位数,则前面用“0"填充,例0001
#auto_increment: 表示此字段为自增长字段,即每条记录自动递增1,默认从1开始递增;自增长字段数据不可以重复;自增长字段必须是主键;如添加的记录数据没有指定此字段的值且添加失败也会自动递增一次
#unique key: 表示此字段唯一键约束,此字段数据不可以重复;一张表中只能有一个主键,但是一张表中可以有多个唯一键
#not null:表示此字段不允许为NULL
-------------------------------------------------------------------------------------------------

8. Advanced database operations

1. Advanced operation of data table

1.克隆表,将数据表的数据记录生成到新的表中
方法一:
create table test01 like CLASS01;       #通过 LIKE 方法,复制CLASS01表结构生成test01表
insert into test01 select * from CLASS01;

方法二:
CREATE TABLE test02 (SELECT * from CLASS01);

show create table test02\G      #获取数据表的表结构、索引等信息
SELECT * from test02;

2.清空表,删除表内的所有数据
方法一
delete from test01;
#DELETE清空表后,返回的结果内有删除的记录条目;DELETE工作时是一行一行的删除记录数据的;如果表中有自增长字段,使用DELETE FROM删除所有记录后,再次新添加的记录会从原来最大的记录ID后面继续自增写入记录。

方法二:
truncate table test01;
#TRUNCATE清空表后,没有返回被删除的条目;TRUNCATE工作时是将表结构按原样重新建立,因此在速度上TRUNCATE会比DELETE清空表快;使用TRUNCATE TABLE清空表内数据后,ID会从1开始重新记录。

3.创建临时表
临时表创建成功之后,使用 SHOW TABLES 命令是看不到创建的临时表的,临时表会在连接退出后被销毁。
如果在退出连接之前,也可以可执行增删改查等操作,比如使用DROP TABLE语句手动直接删除临时表。

CREATE TEMPORARY TABLE 表名 (字段1 数据类型,字段2 数据类型[,...][,PRIMARY KEY (主键名)]);

例:
create temporary table test03 (
id int(4) zerofill primary key auto_increment,
name varchar(10) not null,
cardid int(18) not null unique key,
hobby varchar (50));

insert into test03 values (1,'zhangsan‘,123456,'running’);

select * from test03;
show tables;

quit
select * from test03;

4.创建外键约束,保证数据的完整性和一致性

外键的定义:如果同一个属性字段X在表一中是主键,而在表二不是主键,则字段X称为表二的外键。

主键表和外键表的理解:
1)以公共关键字作主键的表为主键表(父表,主表)
2)以公共关键字作外键的表为外键表(从表、外表)

注意:与外键关联的主表的字段必须设置为主键。要求从表不能是临时表,主从表的字段具备相同的数据类型、字符长度和约束。

#创建主表test04
create table test04 (hobid int(4),hobname varchar(50));

#创建从表test05
create table test05 (id int(4) primary key auto_increment,name varchar(10),age int(3),hobid int(4));

#为主表test04添加一个主键约束。主键名建议以 “PK_” 开头。
alter table test04 add constraint PK_hobid primary key (hobid);

#为从表test05表添加外键,并将test05 表的hobid 字段和test04 表的hobid字段建立外键关联。外键名建议以 “FK_” 开头。
alter table test05 add constraint FK_hob foreign key (hobid) references test04 (hobid);

desc test05;

#插入新的数据记录时,要先主表再从表
insert into test04 values(1,'runing');
insert into test05 values(1,'zhangsan',18,1);

#删数数据记录时,要先从表再主表,也就是说删除主键表时必须先删除其他与之关联的表。
drop tables test05;
drop tables test04;

#查看和删除外键约束
show create table test05; .
alter table test05 drop foreign key FK_hob;
alter table test05 drop key FK_hob;
desc test05;

MySQL中6种常见的约束:
主键约束(primary key)
外键约束(foreign key)
非空约束(not null)
唯一性约束(unique [key|index] )
默认值约束(default) 
自增约束(auto_increment)

2. Database user management

1.新建用户
CREATE USER '用户名'@'来源地址’ [IDENTIFIED BY [PASSWORD] ’密码‘];
------------------------------------------------------------------------------------------------------
'用户名':指定将创建的用户名
'来源地址':指定新创建的用户可在哪些主机上登录,可使用IP地址、网段、主机名的形式,本地用户可用localhost,允许任意主机登录可用通配符%
'密码':若使用明文密码,直接输入'密码',插入到数据库时由Mysql自动加密;
      若使用加密密码,需要先使用SELECT PASSWORD('密码');获取密文,再在语句中添加 PASSWORD '密文';
      若省略“IDENTIFIED BY" 部分,则用户的密码将为空(不建议使用)
------------------------------------------------------------------------------------------------------
CREATE USER 'user1'@'localhost' IDENTIFIED BY '123123';

SELECT PASSWORD('123123');
CREATE USER 'user2'@'localhost' IDENTIFIED BY PASSWORD '*E56A114692FE0DE073F9A1DD68A00EEB9703F3F1';

2.查看用户信息
#创建后的用户保存在mysql数据库的user表里
USE mysql;
SELECT User,authentication_string,Host from user;

3.重命名用户
RENAME USER 'zhangsan'@'localhost' TO 'lisi'@'localhost';

4.删除用户
DROP USER 'lisi'@'localhost';

5.修改当前登录用户密码
SET PASSWORD = PASSWORD('abc123');

6.修改其他用户密码
SET PASSWORD FOR 'user1'@'localhost' = PASSWORD('abc123');

7.忘记root密码的解决办法
1)修改/etc/my.cnf 配置文件,不使用密码直接登录到mysql
vim /etc/my.cnf
[mysqld]
skip-grant-tables       #添加,使登录mysql不使用授权表

systemctl restart mysqld 
mysql       #直接登录

2)使用update 修改root 密码,刷新数据库
UPDATE mysql.user SET AUTHENTICATION STRING = PASSWORD('abc123') where user='root';

FLUSH PRIVILEGES;
quit

mysql -u root -pabc123

注意:最后再把/etc/my.cnf 配置文件里的skip-grant-tables 删除,并重启mysql 服务。

3. Database user authorization

1.授予权限
GRANT语句:专门用来设置数据库用户的访问权限。当指定的用户名不存在时,GRANT语句将会创建新的用户;当指定的用户名存在时,GRANT语句用于修改用户信息。

GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'来源地址' [IDENTIFIED BY '密码'];
------------------------------------------------------------------------------------------------------
#权限列表:用于列出授权使用的各种数据库操作,以逗号进行分隔,如“select,insert,update"。使用“all"表示所有权限,可授权执行任何操作。
#数据库名.表名: 用于指定授权操作的数据库和表的名称,其中可以使用通配符“*”。例如,使用“school.*"表示授权操作的对象为school数据库中的所有表。
#'用户名'@'来源地址': 用于指定用户名称和允许访问的客户机地址,即谁能连接、能从哪里连接。来源地址可以是域名、IP地址,还可使用“%"通配符,表示某个区域或网段内的所有地址,如“%.school.com”、“192.168.80.%”等。
#IDENTIFIED BY: 用于设置用户连接数据库时所使用的密码字符串。在新建用户时,若省略“IDENTIFIED BY" 部分,则用户的密码将为空。
------------------------------------------------------------------------------------------------------
#允许用户zhangsan在本地查询school数据库中所有表的数据记录,但禁止查询其他数据库中的表的记录。
GRANT select ON school.* TO 'zhangsan'@'localhost' IDENTIFIED BY '123456';

#允许用户lisi 在所有终端远程连接mysql ,并拥有所有权限。
GRANT ALL [PRIVILEGES] ON *.* TO 'lisi'@'%' IDENTIFIED BY '123456';

flush privileges;
quit

mysql -u zhangsan -p123456
use school;
show tables;
select * from CLASS01;

2.查看权限
SHOW GRANTS FOR '用户名'@'来源地址';

例:
SHOW GRANTS FOR 'lisi'@'%';

3.撤销权限
REVOKE 权限列表 ON 数据库名.表名 FROM '用户名'@'来源地址';

例:
REVOKE ALL ON *.* FROM 'lisi'@'%';
SHOW GRANTS FOR 'lisi'@'%';
#USAGE 权限只能用于数据库登陆,不能执行任何操作;USAGE权限不能被回收,即REVOKE不能删除用户。

flush privileges;

Guess you like

Origin blog.csdn.net/qq_35456705/article/details/113668170