MySQL数据库管理 二

1、数据表高级操作

(1)克隆表

方法一:
create table 新表名 like 旧表名;                #克隆表结构
insert into 新表名 select * from 旧表名;     #克隆表数据
 
#此方法能保证 新表的表结构、表数据 跟旧表都是一致的
 
方法二:
CREATE TABLE 新表名 (SELECT * from 旧表名);
 
#此方法创建的新表的表数据和旧表是一样的,但可能会出现新表的表结构和旧表的不一致
 
show create table test02\G                    #获取数据表的表结构、索引等信息
SELECT * from test02;

mysql> show tables;
+-----------------+
| Tables_in_zx101 |
+-----------------+
| zx              |
+-----------------+
1 row in set (0.00 sec)

mysql> select * from zx;
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | zx   | 男   |   22 |
|  2 | ctt  | 女   |   23 |
+----+------+------+------+
2 rows in set (0.00 sec)

mysql> create table zx1 like zx;    ##复制表
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+-----------------+
| Tables_in_zx101 |
+-----------------+
| zx              |
| zx1             |
+-----------------+
2 rows in set (0.00 sec)

mysql> insert into zx1 select * from zx;  ##复制表数据
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from zx1;
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | zx   | 男   |   22 |
|  2 | ctt  | 女   |   23 |
+----+------+------+------+
2 rows in set (0.00 sec)

mysql> create table zx2 (select * from zx);   ##或者直接复制表和数据但可能会出现两个表的结构不一致
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from zx2;
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | zx   | 男   |   22 |
|  2 | ctt  | 女   |   23 |
+----+------+------+------+
2 rows in set (0.00 sec)

mysql>

(2)清空表数据

方法一:
delete from xy102;
#DELETE清空表后,返回的结果内有删除的记录条目;DELETE工作时是一行一行的删除记录数据的;如果表中有自增长字段,使用DELETE FROM 删除所有记录后,再次新添加的记录会从原来最大的记录 ID 后面继续自增写入记录。
 
方法二:
truncate table xy102;
#TRUNCATE 清空表后,没有返回被删除的条目;TRUNCATE 工作时是将表结构按原样重新建立,因此在速度上 TRUNCATE 会比 DELETE 清空表快;使用 TRUNCATE TABLE 清空表内数据后,ID 会从 1 开始重新记录。

方法一

mysql>  create table zx4(id int AUTO_INCREMENT, name varchar(20), sex char(2), age int, primary key(id));   ##设置id自增长
Query OK, 0 rows affected (0.00 sec)

自己添加表内容

mysql> select * from zx4;
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | jlh  | 男   |   24 |
|  2 | zx   | 男   |   22 |
|  3 | zyr  | 男   |   20 |
|  4 | tc   | 男   |   19 |
+----+------+------+------+
4 rows in set (0.00 sec)

mysql> show create table zx4;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                           |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| zx4   | CREATE TABLE "zx4" (
  "id" int(11) NOT NULL AUTO_INCREMENT,
  "name" varchar(20) DEFAULT NULL,
  "sex" char(2) DEFAULT NULL,
  "age" int(11) DEFAULT NULL,
  PRIMARY KEY ("id")
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 |   ##自增长数据为5
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> delete from zx4;   ##删除表数据
Query OK, 4 rows affected (0.00 sec)

mysql> show create table zx4;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                           |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| zx4   | CREATE TABLE "zx4" (
  "id" int(11) NOT NULL AUTO_INCREMENT,
  "name" varchar(20) DEFAULT NULL,
  "sex" char(2) DEFAULT NULL,
  "age" int(11) DEFAULT NULL,
  PRIMARY KEY ("id")
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 |  ##自增长数据仍为5
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> insert into zx4(name, sex, age) values( 'tc', '男', 19);
Query OK, 1 row affected (0.00 sec)

mysql> select * from zx4;     ##添加数据时id按之前的数据自增1
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  5 | tc   | 男   |   19 |
+----+------+------+------+
1 row in set (0.00 sec)

mysql>

方法二

mysql> truncate table zx4;
Query OK, 0 rows affected (0.01 sec)

mysql> show create table zx4;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                          |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| zx4   | CREATE TABLE "zx4" (
  "id" int(11) NOT NULL AUTO_INCREMENT,   ##id为自增长
  "name" varchar(20) DEFAULT NULL,
  "sex" char(2) DEFAULT NULL,
  "age" int(11) DEFAULT NULL,
  PRIMARY KEY ("id")
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |  
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> insert into zx4(name, sex, age) values( 'tc', '男', 19);
Query OK, 1 row affected (0.00 sec)

mysql> select * from zx4;    ##添加内容id从1开始
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | tc   | 男   |   19 |
+----+------+------+------+
1 row in set (0.00 sec)

mysql>

(3)创建临时表

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

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

创建临时表,但show tables;查不到

mysql>  create temporary table linshi(id int AUTO_INCREMENT, name varchar(20), sex char(2), age int, pri
mary key(id));
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+-----------------+
| Tables_in_zx101 |
+-----------------+
| zx              |
| zx1             |
| zx2             |
| zx4             |
+-----------------+
4 rows in set (0.00 sec)

mysql>

临时表可以进行增删改查操作

mysql> insert into linshi values(1, 'tc', '男', 19);
Query OK, 1 row affected (0.00 sec)

mysql> insert into linshi values(2, 'zx', '男', 20);
Query OK, 1 row affected (0.00 sec)

mysql> select * from linshi;
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | tc   | 男   |   19 |
|  2 | zx   | 男   |   20 |
+----+------+------+------+
2 rows in set (0.00 sec)

mysql> delete from linshi where id=2;
Query OK, 1 row affected (0.00 sec)

mysql> select * from linshi;
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | tc   | 男   |   19 |
+----+------+------+------+
1 row in set (0.00 sec)

mysql>

2、外键约束(保证数据的完整性和一致性)

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

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

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

(1)创建主从表

#创建主表 class
create table class (name varchar(10), price int);
 
#创建从表 student
create table student (id int, username varchar(20), ageint, sex char(2), classname varchar(10));
 
#为主表class添加一个主键约束,主键名建议以“PK_”开头,可以省略不写,系统会自动分配一个名称
alter table class add primary key (name);
 
#为从表student表添加外键,并将class表的name字段和 student表的classname字段建立外键关联。外键名建议以“FK_”开头,可以省略不写,系统会自动分配一个名称
alter table student add foreign key (classname) references class(name);
 
desc class;   #查看主键表的表结构
desc student;      #查看外键表的表结构
show create table student;   #可以查看表结构的详细信息

mysql> create table class (name varchar(10), price int);
Query OK, 0 rows affected (0.01 sec)

mysql> create table student (id int, username varchar(20), age int, sex char(2), classname varchar(10));

Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> alter table class add primary key (name);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table student add foreign key (classname) references class(name);
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table class\G
*************************** 1. row ***************************
       Table: class
Create Table: CREATE TABLE "class" (
  "name" varchar(10) NOT NULL,
  "price" int(11) DEFAULT NULL,
  PRIMARY KEY ("name")
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> show create table student\G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE "student" (
  "id" int(11) DEFAULT NULL,
  "username" varchar(20) DEFAULT NULL,
  "age" int(11) DEFAULT NULL,
  "sex" char(2) DEFAULT NULL,
  "classname" varchar(10) DEFAULT NULL,
  KEY "classname" ("classname"),
  CONSTRAINT "student_ibfk_1" FOREIGN KEY ("classname") REFERENCES "class" ("name")
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

(2)主从表中插入数据

#插入新的数据记录时,要先主表再从表
insert into class values('云计算', 24000);
insert into class values('JAVA', 25000);
insert into student values(1, 'zhangsan',  2, '男', 'JAVA');

mysql> insert into class values('云计算', 24000);
Query OK, 1 row affected (0.00 sec)

mysql> insert into class values('JAVA', 25000);
Query OK, 1 row affected (0.00 sec)

mysql> select * from class;
+-----------+-------+
| name      | price |
+-----------+-------+
| JAVA      | 25000 |
| 云计算    | 24000 |
+-----------+-------+
2 rows in set (0.00 sec)

mysql> insert into student values(1, 'zhangsan', 20, '男', 'JAVA');
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;
+------+----------+------+------+-----------+
| id   | username | age  | sex  | classname |
+------+----------+------+------+-----------+
|    1 | zhangsan |   20 | 男   | JAVA      |
+------+----------+------+------+-----------+
1 row in set (0.00 sec)

mysql> insert into student values(2, 'lisi', 21, '男', 'JSP');  ##classname的值只能是class表中name值中的两个之一
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ("zx101"."student", CONSTRAINT "student_ibfk_1" FOREIGN KEY ("classname") REFERENCES "class" ("name"))
mysql>

(3)主从表中删除数据

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

delete from student where id=1;

delete from class where name='JAVA';

mysql> select * from student;
+------+----------+------+------+-----------+
| id   | username | age  | sex  | classname |
+------+----------+------+------+-----------+
|    1 | zhangsan |   20 | 男   | JAVA      |
+------+----------+------+------+-----------+
1 row in set (0.00 sec)

mysql> insert into student values(2, 'lisi', 21, '男', '云计算');
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+------+----------+------+------+-----------+
| id   | username | age  | sex  | classname |
+------+----------+------+------+-----------+
|    1 | zhangsan |   20 | 男   | JAVA      |
|    2 | lisi     |   21 | 男   | 云计算    |
+------+----------+------+------+-----------+
2 rows in set (0.00 sec)

mysql> delete from class where name='JAVA'; ##想要删除主从表中的数据,必须先删除从表中外键约束的内容,再删除主键内容,负责无法删除
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails ("zx101"."student", CONSTRAINT "student_ibfk_1" FOREIGN KEY ("classname") REFERENCES "class" ("name"))
mysql> delete from student where id=1;
Query OK, 1 row affected (0.00 sec)

mysql> delete from class where name='JAVA';
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+------+----------+------+------+-----------+
| id   | username | age  | sex  | classname |
+------+----------+------+------+-----------+
|    2 | lisi     |   21 | 男   | 云计算    |
+------+----------+------+------+-----------+
1 row in set (0.00 sec)

mysql> select * from class;
+-----------+-------+
| name      | price |
+-----------+-------+
| 云计算    | 24000 |
+-----------+-------+
1 row in set (0.00 sec)

mysql>

(4)删除外键约束

#查看和删除外键约束

show create table student;

desc student;

alter table student drop foreign key student_ibfk_1;

alter table student drop key classname;

mysql> show create table student\G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE "student" (
  "id" int(11) DEFAULT NULL,
  "username" varchar(20) DEFAULT NULL,
  "age" int(11) DEFAULT NULL,
  "sex" char(2) DEFAULT NULL,
  "classname" varchar(10) DEFAULT NULL,
  KEY "classname" ("classname"),
  CONSTRAINT "student_ibfk_1" FOREIGN KEY ("classname") REFERENCES "class" ("name")
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> alter table student drop foreign key student_ibfk_1; ##想删除外键,先删除外键别名
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table student\G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE "student" (
  "id" int(11) DEFAULT NULL,
  "username" varchar(20) DEFAULT NULL,
  "age" int(11) DEFAULT NULL,
  "sex" char(2) DEFAULT NULL,
  "classname" varchar(10) DEFAULT NULL,
  KEY "classname" ("classname")
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> alter table student drop key classname; ##再删除外键键名
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table student\G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE "student" (
  "id" int(11) DEFAULT NULL,
  "username" varchar(20) DEFAULT NULL,
  "age" int(11) DEFAULT NULL,
  "sex" char(2) DEFAULT NULL,
  "classname" varchar(10) DEFAULT NULL  ##外键被删除
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql>

3、数据库用户管理

(1)新建用户

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

mysql> create user 'zx'@'%' identified by 'abc123';
Query OK, 0 rows affected (0.00 sec)

mysql> select user,host,authentication_string from mysql.user;
+---------------+-----------+-------------------------------------------+
| user          | host      | authentication_string                     |
+---------------+-----------+-------------------------------------------+
| root          | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys     | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| root          | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| zx            | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
+---------------+-----------+-------------------------------------------+
5 rows in set (0.00 sec)

mysql>

(2)查看用户信息

#创建后的用户保存在 mysql 数据库的 user 表里
USE mysql;
SELECT User,authentication_string,Host from user;
#查看当前登录用户
select user();
[root@zx1 ~]# mysql -u zx -pabc123 -h 20.0.0.10
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select user();
+--------------+
| user()       |
+--------------+
| zx@20.0.0.10 |
+--------------+
1 row in set (0.00 sec)

mysql>

(3)重命名用户

RENAME USER '用户名'@'来源地址' TO '新用户名'@'来源地址';

mysql> select user,host,authentication_string from mysql.user;
+---------------+-----------+-------------------------------------------+
| user          | host      | authentication_string                     |
+---------------+-----------+-------------------------------------------+
| root          | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys     | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| root          | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| zx            | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
+---------------+-----------+-------------------------------------------+
5 rows in set (0.00 sec)

mysql> rename user 'zx'@'%' to 'zx1'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> select user,host,authentication_string from mysql.user;
+---------------+-----------+-------------------------------------------+
| user          | host      | authentication_string                     |
+---------------+-----------+-------------------------------------------+
| root          | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys     | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| root          | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| zx1           | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
+---------------+-----------+-------------------------------------------+
5 rows in set (0.00 sec)

mysql>

(4)删除用户

DROP USER '用户名'@'来源地址';

mysql> rename user 'zx'@'%' to 'zx1'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> select user,host,authentication_string from mysql.user;
+---------------+-----------+-------------------------------------------+
| user          | host      | authentication_string                     |
+---------------+-----------+-------------------------------------------+
| root          | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys     | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| root          | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| zx1           | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
+---------------+-----------+-------------------------------------------+
5 rows in set (0.00 sec)

mysql> drop user 'zx1'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> select user,host,authentication_string from mysql.user;
+---------------+-----------+-------------------------------------------+
| user          | host      | authentication_string                     |
+---------------+-----------+-------------------------------------------+
| root          | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys     | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| root          | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
+---------------+-----------+-------------------------------------------+
4 rows in set (0.00 sec)

(5)修改当前登录用户密码

方法1

SET PASSWORD = PASSWORD('123456');

方法2

ALTER USER 'root'@'localhost' IDENTIFIED BY 'abc123';

方法一

mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

mysql> set password = password('123456');
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> quit
Bye
[root@zx1 ~]# mysql -u root -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

方法二

mysql> alter user 'root'@'localhost' identified by 'abc123';
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
[root@zx1 ~]# mysql -u root -pabc123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

(6)修改其他用户密码

SET PASSWORD FOR 'user1'@'localhost' = PASSWORD('abc123');

mysql> create user 'zx'@'%' identified by 'abc123';
Query OK, 0 rows affected (0.01 sec)

mysql> select user,host,authentication_string from mysql.user;
+---------------+-----------+-------------------------------------------+
| user          | host      | authentication_string                     |
+---------------+-----------+-------------------------------------------+
| root          | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys     | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| root          | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| zx            | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
+---------------+-----------+-------------------------------------------+
5 rows in set (0.00 sec)

mysql> alter user 'root'@'localhost' identified by 'abc123';
Query OK, 0 rows affected (0.00 sec)

mysql> set password for 'zx'@'%' = password('123456');
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql>

(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

[root@zx1 ~]# vim /etc/my.cnf
[root@zx1 ~]# systemctl restart mysqld
[root@zx1 ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> update mysql.user set authentication_string = password('abc123') where user='root';
Query OK, 0 rows affected, 1 warning (0.00 sec)
Rows matched: 2  Changed: 0  Warnings: 1

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
[root@zx1 ~]# mysql -u root -pabc123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

在server-id = 1下一行添加此内容

4、数据库用户授权

(1)授予权限

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

GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'来源地址' [IDENTIFIED BY '密码'];
#mysql 5.7或之前的版本支持使用 IDENTIFIED BY '密码' 创建用户和授予权限,8.0开始只能 用于授予权限。

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

zx用户只有登录权限

[root@zx1 ~]# mysql -u zx -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.00 sec)

mysql>

进入root用户给zx用户授权

[root@zx1 ~]# mysql -u root -pabc123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| zx0105             |
| zx101              |
+--------------------+
6 rows in set (0.00 sec)

mysql> use zx101;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-----------------+
| Tables_in_zx101 |
+-----------------+
| class           |
| student         |
| zx              |
| zx1             |
| zx2             |
| zx4             |
+-----------------+
6 rows in set (0.00 sec)

mysql> grant select on zx101.* to 'zx'@'%'; ##授权zx用户数据库zx101的select权限
Query OK, 0 rows affected (0.01 sec)

mysql> quit
Bye
[root@zx1 ~]# mysql -u zx -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select user();
+--------------+
| user()       |
+--------------+
| zx@localhost |
+--------------+
1 row in set (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| zx101              |
+--------------------+
2 rows in set (0.00 sec)

mysql> use zx101;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-----------------+
| Tables_in_zx101 |
+-----------------+
| class           |
| student         |
| zx              |
| zx1             |
| zx2             |
| zx4             |
+-----------------+
6 rows in set (0.00 sec)

mysql> select * from zx101.zx;
+----+------+------+------+
| id | name | sex  | age  |
+----+------+------+------+
|  1 | zx   | 男   |   22 |
|  2 | ctt  | 女   |   23 |
|  3 | jlh  | 男   |   21 |
|  4 | zyr  | 男   |   20 |
+----+------+------+------+
4 rows in set (0.00 sec)

mysql> delect from zx101.zx where id=1; ##只有select的权限,没有其他权限
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'delect from zx101.zx where id=1' at line 1
mysql>


(2)查看权限

SHOW GRANTS FOR 用户名@来源地址;

[root@zx1 ~]# mysql -u root -pabc123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.7.44 Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select user,host,authentication_string from mysql.user;
+---------------+-----------+-------------------------------------------+
| user          | host      | authentication_string                     |
+---------------+-----------+-------------------------------------------+
| root          | localhost | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| mysql.session | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| mysql.sys     | localhost | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| root          | %         | *6691484EA6B50DDDE1926A220DA01FA9E575C18A |
| zx            | %         | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
+---------------+-----------+-------------------------------------------+
5 rows in set (0.00 sec)

mysql> show grants for 'zx'@'%';
+---------------------------------------+
| Grants for zx@%                       |
+---------------------------------------+
| GRANT USAGE ON *.* TO 'zx'@'%'        |
| GRANT SELECT ON "zx101".* TO 'zx'@'%' |
+---------------------------------------+
2 rows in set (0.00 sec)

mysql>

(3)撤销权限

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

mysql> revoke select on zx101.* from 'zx'@'%';
Query OK, 0 rows affected (0.00 sec)

mysql> show grants for 'zx'@'%';
+--------------------------------+
| Grants for zx@%                |
+--------------------------------+
| GRANT USAGE ON *.* TO 'zx'@'%' |
+--------------------------------+
1 row in set (0.00 sec)

mysql>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/722721.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Python 数据可视化 多色散点图

Python 数据可视化 多色散点图 fig, ax plt.subplots() max_line max([max(merged_df[unif_ref_value]), max(merged_df[unif_rust_value])]) min_line min([max(merged_df[unif_ref_value]), max(merged_df[unif_rust_value])]) ax.plot([min_line, max_line], [min_line, …

【C语言】二维数组(详解)

目录 1. 二维数组的创建 1.1 二维数组的概念 1.2 二维数组的创建 2. 二维数组的初始化 2.1 不完全初始化 2.2 完全初始化 2.3 按照行初始化 2.4 初始化时能省略行,但不能省略列 3. 二维数组的使用 3.1 二维数组下标 3.2 二维数组…

【2024】kafka streams结合案例分析进行实际项目开发使用(3)

💻目录 一、前沿介绍二、代码实现1、依赖2、实体类2.1、Transaction2.2、 TransactionKey2.3、TransactionPattern2.4、CustomerReward 3、序列化工具类3.1、序列化3.2、反序列化3.3、Serde仓库 4、具体streams实现5、其他测试使用5.1、生产者5.2、日志文件 6、创建…

背景渐变动画登录页

b站视频演示效果: 效果图: 完整代码: <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>背景…

MySQL全解(基础)-(MySQL的安装与配置,数据库基础操作(CRUD,聚合,约束,联合查询),索引,事务)

MySQL安装与配置 1.数据库介绍 存储数据用文件就可以了&#xff0c;为什么还要弄个数据库? 文件保存数据有以下几个缺点&#xff1a; 文件的安全性问题 文件不利于数据查询和管理 文件不利于存储海量数据 文件在程序中控制不方便数据库存储介质&#xff1a; 磁盘 内存 为了…

天翼云8080、80端口用不了的问题

天翼云8080、80端口用不了的问题 前言&#xff1a;前段时间天翼云搞了活动&#xff0c;原来公司用的华为云老板说太贵了也快到期了&#xff0c;就换了天翼云的服务器。 排查&#xff1a; 安全组开放 80 8080 防火墙查看 没有问题 nginx nacos dcoker等停了 查看监听端口 发现…

web标准与浏览器前缀

目录 W3Cweb标准&#xff1a;是敌还是友人员结构标准制订的流程 css3&#xff0c;css4的传说css3 浏览器前缀&#xff1a;失败的产物关于渐进增强和优雅降级 W3C 万维网最初是由欧洲核子研究组织的一个项目发展起来的&#xff0c;在那里蒂姆伯纳斯-李开发出第一个万维网的雏形…

超声波清洗机有用吗?四大主流超声波清洗机终极PK大测评!

超声波清洗机是通过产生的超声波对于液体不断动作的一个过程&#xff0c;水分子在超声波的震动下互相碰撞挤压&#xff0c;从而发生空化作用对物体表面的污迹进行乳化剥离&#xff01;相比手洗的方式&#xff0c;超声波能够深入夹缝清洁&#xff0c;清洁程度非常高&#xff01;…

充电学习—8、Type-C TCPC TCPCI

TCPC是usb Type-C port controller&#xff1b; 通用串行总线C型端口控制器 TCPCI是tcpc控制器接口规范&#xff1b; TCPC是个功能块&#xff0c;其中含有VBUS和VCONN的电源控制功能&#xff0c;CC信号的处理 逻辑&#xff0c;PD应用中的BMC物理层和协议层&#xff08;PD信息…

FlowUs:打造沉浸式协作体验感受

直观的用户体验 从我个人的角度来看&#xff0c;FlowUs的界面设计非常符合现代审美&#xff0c;简洁而不失功能性。每次打开FlowUs&#xff0c;我都能迅速找到我需要的功能&#xff0c;这大大提升了我的工作效率。 实时协作的流畅性 在FlowUs中&#xff0c;我最喜欢的功能之一就…

13.4 内存管理

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」…

c++参考std::string自己设计类hstring

目录 一、前言 二、设计需求 三、设计思想 1.功能一 1.功能二 四、设计过程 1.类hstring搭建 2. 实现有参构造函数 3. 实现副本构造函数 4.完整代码 五、结束语 一、前言 在c中有很多的库&#xff0c;但是在有些时候呢&#xff0c;我们一定要学会自己去设计库&#…

抖音素材网站平台有哪些?素材下载网站库分享

在这个视觉信息充斥的时代&#xff0c;抖音已经成为众多自媒体人展示才华的舞台。要在众多创作者中脱颖而出&#xff0c;不仅需要独特的创意&#xff0c;还需要优质的素材来支持你的内容制作。今天&#xff0c;我将介绍几个为抖音视频提供高品质素材的网站&#xff0c;包括国内…

Python构造TCP三次握手、传输数据、四次挥手pcap数据包并打乱顺序

Python构造数据包&#xff0c;包含&#xff1a; TCP三次握手、 传输数据、 四次挥手 实现 随机乱序TCP数据包 from scapy.all import * from scapy.all import Ether, IP, TCP, UDP, wrpcap from abc import ABC, abstractmethod import random import dpkt from scapy.all…

训练营第四十二天| 583. 两个字符串的删除操作72. 编辑距离647. 回文子串516.最长回文子序列

583. 两个字符串的删除操作 力扣题目链接(opens new window) 给定两个单词 word1 和 word2&#xff0c;找到使得 word1 和 word2 相同所需的最小步数&#xff0c;每步可以删除任意一个字符串中的一个字符。 示例&#xff1a; 输入: "sea", "eat"输出: …

QT6不自动生成pro文件

安装了QT的新版本结果他不自动生成pro文件了导致下次打开很复杂 记得在创建时选择qmake&#xff0c;因为新版默认cmake

宝塔软件默认安装位置

自带的JDK /usr/local/btjdk/jdk8Tomcat 各个版本都在bttomcat这个文件夹下面&#xff0c;用版本区分。tomcat_bak8是备份文件 /usr/local/bttomcat/tomcat8nginx /www/server/nginxnginx配置文件存放目录 /www/server/panel/vhost/nginxredis /www/server/redismysql /…

财讯杂志财讯杂志社财讯编辑部2024年第6期目录查询

财税研究 “互联网税务”模式在企业税务管理中的应用 陈飞; 1-3 国有企业税务稽查的问题与对策研究 梁涵瑜; 4-6 税务师事务所执业质量内部控制优化路径及风险防范 万晓玲; 7-9《财讯》投稿&#xff1a;cnqikantg126.com 基于全过程的新能源电力投资企业税务筹…

宝塔面板使用技巧(pure-FTP)上传文件和文件夹默认权限644的修改

前言 科技在进步各种各样的开源软件和库让我们应接不暇&#xff0c;我估计现在所有做php开发的人员都知道宝塔面板&#xff0c;我就经常用&#xff0c;但是不知道大家出现过一个问题不就是在我们开发过程中需要实时的给服务器上传我们开发的文件那么就涉及到了宝塔自带的pure-F…

BC-Linux 8.6最小化安装的服务器启用GNOME图形化界面

本文记录了BC-Linux 8.6最小化安装的服务器如何启用GNOME图形化界面的过程。 一、服务器环境 1、系统版本 [rootlocalhost ~]# cat /etc/os-release NAME"BigCloud Enterprise Linux" VERSION"8.6 (Core)" ID"bclinux" ID_LIKE"rhel fe…