The first ***Mysql preparation basics

1. Common concepts of database

1. DB: database, a container for storing data.

2. DBMS: database management system, used to manage or create DB.

3. SQL: Structured query language, which is used to communicate with databases, a language common to almost all mainstream database software.

4. The SQL language is divided into:

  • DQL (data query language): select related statements in the data query language;
  • DML (data manipulate language): data manipulation statements insert, update, delete statements;
  • DDL (data define language): data definition language create, drop, alter statement;
  • TCL (transaction control language): transaction control language set autocommit=0, start transcation, savepoint, commit, rollback;

Second, the characteristics of database storage data

1. The data is stored in the table, and the table is stored in the database;

2. There can be multiple tables in a library, and each table has a unique table name to identify itself;

3. There are one or more columns in the table, which are also called "fields", which are equivalent to attributes in java;

4. Each row of data in the table is equivalent to an object in java

Three, some commonly used commands in Mysql

win+R , cmd

Entering services.msc will open the service window, find the MySQL service in the service window, and right-click to start or stop it.

Stop command: net stop mysql

Start command: net start mysql

If an error is reported: system error 5 occurs in the mysql startup command. access denied.

This situation is because the current user operation authority is too low, running cmd as an administrator can be normal.

1、mysql登录
mysql -h localhost -P 3306 -u root -p
说明:
-P大写的P后面跟上端口; 
如果是登录本地账号,ip和端口可以省略,如:mysql -u 用户名 -p
可以通过上面的命令连接原创机器的mysql
2、查看数据库版本
未登录状态:mysql --version  或  mysql -V
登录状态:select version();
3、显示所有数据库
show databases;

4、进入指定的库
use 库名;

5、显示当前库中的所有表
show tables;

6、查看其他库中的所有表
show tables from 库名;

7、查看表的创建语句
show create table 表名;

8、查看表结构
desc 表名;

9、查看当前所在库
select database();

10、查看当前mysql支持的存储引擎
show engines;

11、查看系统变量及其值
show variables;

12、查看某个系统变量
show variables like '变量名';
eg:
show variables like 'wait_timeout';
show variables like '%wait_timeout%t';
  • It’s not case sensitive. It is recommended that keywords be capitalized, indicating that the column names are in lowercase
  • Each command should end with an English semicolon
  • Each naming is indented or wrapped as needed
  • Single-line comment: #note text or-comment text, you need to add a space here;
  • Multi-line comment: /* comment text*/

Four, data types in MySQL

Mainly include the following five categories:

  • Integer types: bit, bool, tinyint, smallint, mediumint, int, bigint
  • Floating point types: float, double, decimal
  • String types: char, varchar, tinyblob, blob, mediumblob, longblob, tinytext, text, mediumtext, longtext
  • Date type: Date, TateTime, TimeStamp, Time, Year
  • Other data types

Example 1: Integer types-signed and unsigned types

mysql> create database test;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |      |
| comperformance     |
| covid19_beta       |
| db_dorm            |
| kettle_demo        |
| mysql              |
| test               |
+--------------------+
8 rows in set (0.00 sec)

mysql> use test;
Database changed

mysql># 有符号类型
mysql> create table demo1(
    -> c1 tinyint
    -> );
Query OK, 0 rows affected (0.11 sec)

mysql> create table demo2(c2 tinyint);
Query OK, 0 rows affected (0.42 sec)

mysql> insert into demo1 values(-pow(2,7)),(pow(2,3)-3);
Query OK, 2 rows affected (0.06 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from demo1;
+------+
| c1   |
+------+
| -128 |
|    5 |
+------+
2 rows in set (0.00 sec)


mysql># 无符号类型
mysql> create table demo3(c1 tinyint unsigned);
Query OK, 0 rows affected (0.19 sec)

mysql> insert into demo3 values(-1);
ERROR 1264 (22003): Out of range value adjusted for column 'c1' at row 1

mysql> insert into demo3 values (pow(2,8)+1);
ERROR 1264 (22003): Out of range value adjusted for column 'c1' at row 1

mysql> insert into demo3 values(0),(pow(2,8)-1);
Query OK, 2 rows affected (0.09 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from demo3;
+------+
| c1   |
+------+
|    0 |
|  255 |
+------+
2 rows in set (0.00 sec)

mysql># C1是无符号的tinyint类型的,插入了负数会报错

Example 2: Floating point type-error-prone, be careful

The float numeric type is used to represent single-precision floating-point values, while the double numeric type is used to represent double-precision floating-point values. Both float and double are floating-point types, but decimal is a fixed-point type. Floating-point and fixed-point types can be expressed by adding (M, D) to the name of the type. M indicates the total length of the value, D indicates the length after a few points, and M and D are also called precision and standard. degree.

When the precision is not specified for float and double, the default will be displayed according to the actual precision. However, when the precision is not specified for DECIMAL, the default integer is 10 and the number of minutes is 0.

mysql> use test;
Database changed
mysql> create table test5(a float(5,2),b double(5,2),c decimal(5,2));
Query OK, 0 rows affected (0.18 sec)

mysql> insert into test5 values (1,1,1),(2.1,2.1,2.1),(3.123,3.123,3.123),(4.125,4.125,4.125),(5.115,5.115,5.115),(6.126,6.126,6.126),(7.116,7.116,7.116),(8.1151,8.1151,8.1151),(9.1251,9.1251,9.1251),(10.11501,10.11501,10.11501),(11.12501,11.12501,11.12501);
Query OK, 11 rows affected, 9 warnings (0.04 sec)
Records: 11  Duplicates: 0  Warnings: 9

mysql> select * from test5;
+-------+-------+-------+
| a     | b     | c     |
+-------+-------+-------+
|  1.00 |  1.00 |  1.00 |
|  2.10 |  2.10 |  2.10 |
|  3.12 |  3.12 |  3.12 |
|  4.13 |  4.13 |  4.13 |
|  5.12 |  5.12 |  5.12 |
|  6.13 |  6.13 |  6.13 |
|  7.12 |  7.12 |  7.12 |
|  8.12 |  8.12 |  8.12 |
|  9.13 |  9.13 |  9.13 |
| 10.12 | 10.12 | 10.12 |
| 11.13 | 11.13 | 11.13 |
+-------+-------+-------+
11 rows in set (0.00 sec)

######################################################################
说明(注意看):
c是decimal类型,认真看⼀下输⼊和输出,发现decimal采⽤的是四舍五⼊认真看⼀下a和b的输⼊和输出,不是四舍五⼊,float和double采⽤的是四舍六⼊五成双,decimal插⼊的数据超过精度之后会触发警告。

什么是四舍六⼊五成双?
就是5以下舍弃,5以上进位,如果需要处理数字为5的时候,需要看5后⾯是否还有不为0的任何数字,如果有,则直接进位,如果没有,需要看5前⾯的数字,若是奇数则进位,若是偶数则将5舍掉

We remove the (M, D) precision and scale of the floating-point type to see the effect:

mysql> create table test6(a float,b double,c decimal);
Query OK, 0 rows affected (0.17 sec)

mysql> insert into test6 values (1,1,1),(1.234,1.234,1.4),(1.234,0.01,1.5);
Query OK, 3 rows affected, 2 warnings (0.16 sec)
Records: 3  Duplicates: 0  Warnings: 2

mysql> select * from test6;
+-------+-------+------+
| a     | b     | c    |
+-------+-------+------+
|     1 |     1 |    1 |
| 1.234 | 1.234 |    1 |
| 1.234 |  0.01 |    2 |
+-------+-------+------+
3 rows in set (0.00 sec)

#######################################################################
a和b的数据正确插⼊,⽽c被截断了浮点数float、double如果不写精度和标度,则会按照实际显⽰decimal不写精度和标度,⼩数点后⾯的会进⾏四舍五⼊,并且插⼊时会有警告!	

再看看下面的代码:
mysql> select sum(a),sum(b),sum(c) from test5;
+--------+--------+--------+
| sum(a) | sum(b) | sum(c) |
+--------+--------+--------+
|  67.22 |  67.22 |  67.22 |
+--------+--------+--------+
1 row in set (0.00 sec)

mysql> select sum(a),sum(b),sum(c) from test6;
+-----------------+--------+--------+
| sum(a)          | sum(b) | sum(c) |
+-----------------+--------+--------+
| 3.4679999351501 |  2.244 |      4 |
+-----------------+--------+--------+
1 row in set (0.00 sec)
########################################################################
从上⾯sum的结果可以看出float、double会存在精度问题,decimal精度正常的,⽐如银⾏对统计结果要求⽐较精准的建议使⽤decimal。

supplement:

Type N description

In the development, we will encounter some definitions of integer type is int (N), this type of writing is useless in development, we only need to remember two points:

  • No matter how much N is equal to, int only occupies 4 bytes.
  • N represents the display width, which is not enough to be 0 to make up. If the length is exceeded, only the entire number is displayed, but it is only valid if the integer is set to unsigned zerofill.

Example:

mysql> CREATE TABLE test3 ( `a` int, `b` int(5), `c` int(5) unsigned, `d` int(5) zerofill, `e` int(5) unsigned zerofill, `f` int zerofill, `g` int unsigned zerofill );
Query OK, 0 rows affected (0.17 sec)

mysql> insert into test3 values (1,1,1,1,1,1,1),(11,11,11,11,11,11,11),(12345,12345,12345,12345,12345,12345,12345);
Query OK, 3 rows affected (0.14 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from test3;
+-------+-------+-------+-------+-------+------------+------------+
| a     | b     | c     | d     | e     | f          | g          |
+-------+-------+-------+-------+-------+------------+------------+
|     1 |     1 |     1 | 00001 | 00001 | 0000000001 | 0000000001 |
|    11 |    11 |    11 | 00011 | 00011 | 0000000011 | 0000000011 |
| 12345 | 12345 | 12345 | 12345 | 12345 | 0000012345 | 0000012345 |
+-------+-------+-------+-------+-------+------------+------------+
3 rows in set (0.00 sec)

mysql> show create table test3;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                                                                                                                  |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| test3 | CREATE TABLE `test3` (
  `a` int(11) default NULL,
  `b` int(5) default NULL,
  `c` int(5) unsigned default NULL,
  `d` int(5) unsigned zerofill default NULL,
  `e` int(5) unsigned zerofill default NULL,
  `f` int(10) unsigned zerofill default NULL,
  `g` int(10) unsigned zerofill default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql># show create table test3; 输出了表test3的创建语句,和我们原始的创建语句不一样,原始的d字段用的是无符号的,可以看出当时使用了zerofill自动会将无符号变为有符号。

Note: When the output width of int(5) is less than 5, the front side is filled with 0. When n in int(n) is omitted, the width is the length of the decimal notation of the maximum value of the corresponding type, such as bigint. The maximum symbol value is -1 = 18,446,744,073,709,551,615; the length is 20 bits

Date type

String type

The char type occupies a fixed length. If the stored data is of a fixed length, it is recommended to use the char type, such as fixed-length information such as mobile phone numbers and identity certificates.

选⼩不选⼤:⼀般情况下选择可以正确存储数据的最⼩数据类型,越⼩的数据类型通常更快,占⽤磁盘,内存和CPU缓存更⼩。

简单就好:简单的数据类型的操作通常需要更少的CPU周期,例如:整型⽐字符操作代价要⼩得多,因为字符集和校对规则(排序规则)使字符⽐整型⽐较更加复杂。

尽量避免NULL:尽量制定列为NOT	NULL,除⾮真的需要NULL类型的值,有NULL的列值会使得索引、索引统计和值⽐较更加复杂。

浮点类型的建议统⼀选择decimal

记录时间的建议使⽤int或者bigint类型,将时间转换为时间戳格式,如将时间转换为秒、毫秒,进⾏存储,⽅便⾛索引

Five, the commands commonly used by database administrators

1. How mysql permissions work

For security reasons, mysql uses the host name + user name to determine the identity of a user, because it is difficult to determine the identity of a user through the user name in the Internet, but we can use ip Or the host name judges a machine, and a user who comes through this machine can be identified as a user, so the user name + host name is used in mysql to identify the user's identity. When a user sends a command to mysql, mysql uses the user name and source (host) to determine the user's permissions.

2. Authorization verification is divided into two stages:

Phase 1: Connect to the database. At this time, mysql will determine whether you have permission to connect based on your user name and your source (ip or host name);

Phase 2: Initiate request operations to the mysql server, such as create table, select, delete, update, create index, etc. At this time, mysql will determine whether you have permission to operate these instructions;

3. Effective time of authority

The user and permission information is stored in the library named mysql. When mysql is started, these contents are read into the memory and are effective from this time, so if you modify the user and permission information by directly operating these tables, you need to restart mysql Or execute flush privileges; to be effective. After the user logs in, mysql will create a connection with the current user. At this time, the user-related permission information is stored in this connection and stored in the memory. At this time, if the current user is modified in other places The permissions of these changes will not take effect until the next time you log in.

4. Use of common commands

1、用户信息在mysql.user表中
use mysql;
select user,host from user;

2、创建用户
create user 用户名[@主机名] [identified by '密码'];
#主机名默认值%,表示这个用户可以从任何主机连接mysql服务器
#密码可以省略,表示无密码登录
示例1:不指定主机名,表示这个用户可以从任何主机连接mysql服务器
mysql> create user wang;
Query OK, 0 rows affected (0.25 sec)

mysql> select user,host from user;
+------+-----------+
| user | host      |
+------+-----------+
| wang | %         |
| root | localhost |
+------+-----------+
2 rows in set (0.00 sec)

mysql> exit;
Bye

C:\Windows\system32>mysql -uwang
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 50 to server version: 5.0.24a-community-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>
###############################################################################
上⾯创建了⽤户名为wang⽆密码的⽤户,没有指定主机,可以看出host的默认值为%,表⽰wang可以从任何机器登录到mysql中。

⽤户创建之后可以在mysql库中通过select user,host from user;查看到。
###############################################################################
其他示例:
create user 'wang2'@'localhost' identifiled by '123';
说明:wang2的主机为localhost表⽰本机,此⽤户只能登陆本机的mysql	

create user 'wang3'@% identifiled by '123';
说明:wang3可以从任何机器连接到mysql服务器

create user 'wang4'@'192.168.11.%' identifiled by '123';
说明:wang4可以从192.168.11段的机器连接mysql	


3、修改密码
(1)管理员修改
set password for '用户名'@'主机' = password('密码');
(2)create user 用户名[@主机名][identifiled by '密码'];
set password = password('密码');
(3)修改mysql.user表修改密码
user mysql;
update user set authentication_string = password('321') where user = 'wang' and host='%';
flush privileges; # 对用户生效
##5.7中user表中的authentication_string字段表⽰密码,⽼的⼀些版本中密码字段是password。


4、给用户授权
创建用户后,需要给用户授权,才有意义。
grant privileges ON database.table TO 'username'[@'host'] [with grant option]

grant命令说明:
(1)priveleges(权限列表),可以是all,表⽰所有权限,也可以是select、update等权限,多个权限之间⽤逗号分开。
(2)ON ⽤来指定权限针对哪些库和表,格式为数据库.表名,点号前⾯⽤来指定数据库名,点号后⾯⽤来指定表名,*.*表⽰所有数据库所有表。
(3)TO 表⽰将权限赋予某个⽤户,格式为username@host,@前⾯为⽤户名,@后⾯接限制的主机,可以是IP、IP段、域名以及%,%表⽰任何地⽅。
(4)with grant option	这个选项表⽰该⽤户可以将⾃⼰拥有的权限授权给别⼈。注意:经常有⼈在创建操作⽤户的时候不指定with grant option选项导致后来该⽤户不能使⽤grant命令创建⽤户或者给其它⽤户授权。备注:可以使⽤GRANT重复给⽤户添加权限,权限叠加,⽐如你先给⽤户添加⼀个select权限,然后又给⽤户添加⼀个insert权限,那么该⽤户就同时拥有了select和insert权限。

示例:
grant all on *.* to 'test1'@'%';
说明:给test1授权可以操作所有库所有权限,相当于dba	

grant select on seata.* to 'test1'@'%';
说明:test1可以对seata库中所有的表执⾏select	

grant select,update on seata.* to 'test1'@'%';
说明:test1可以对seata库中所有的表执⾏select、update	

grant select(user,host) on mysql.user to 'test1'@'localhost';
说明:test1⽤户只能查询mysql.user表的user,host字段


5、查看用户有哪些权限
(1)show grants for '用户名'[@'主机']
主机可以省,默认值%
eg:show grants for 'test1'@'localhost';

(2)show grants;
查看当前用户权限
eg:show grants;

6、撤销用户的权限
revoke privileges ON database.table FROM '用户名'[@'主机'];
可以先通过show grants命令查询⼀下⽤户对于的权限,然后使⽤revoke命令撤销⽤户对应的权限.
eg:
show grants for 'test1'@'localhost';
revoke select(host) ON mysql.user from test1@localhost;
show grants for 'test1'@'localhost';
上⾯我们先通过grants命令查看test1的权限,然后调⽤revoke命令撤销对mysql.user表host字段的查询权限,最后又通过grants命令查看了test1的权限,和预期结果⼀致。


7、删除用户
(1)drop user'用户名'[@'主机']
eg:drop user test1@localhost;
drop的⽅式删除⽤户之后,⽤户下次登录才生效。

(2)通过删除mysql.user表数据的方式删除
eg:
delete from user where user='用户名' and host='主机';
flush privileges;
注意通过表的⽅式删除的,需要调⽤flush privileges;刷新权限信息(权限启动的时候在内存中保存着,通过表的⽅式修改之后需要刷新⼀下)。

1. Only grant the minimum permissions that can meet the needs to prevent users from doing bad things. If the user only needs to query, then only the select permission is enough. Do not give the user update, insert or delete permissions;

2. When creating a user, restrict the user's login host, usually restricted to a specified IP or internal IP segment;

3. Delete users without passwords when initializing the database, and automatically create some users when the database is installed. These users do not have passwords by default;

4. Set a password that meets the complexity of the password for each user;

5. Regularly clean up unnecessary users, reclaim permissions or delete users;

to sum up

1. Users and permissions do not need to be refreshed through command-based operations, and the next login will take effect automatically;

2. By operating the mode modification and user information of the table in the mysql library, flush privileges need to be invoked; refresh once, the next login will automatically take effect;

3. The method for mysql to identify the user's identity is: user name + host;

4. The host can be omitted in some commands mentioned in this text, and the default value is %, which means all machines;

5. The user and permission information in mysql is in the library named mysql;

Guess you like

Origin blog.csdn.net/qq_46009608/article/details/112966250