MySQL数据库操作

2021/8/26 19:06:25

本文主要是介绍MySQL数据库操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

MySQL数据库操作

目录
  • MySQL数据库操作
    • 一、数据表高级操作
      • 1. 克隆表,将数据表的数据记录生成到新的表中
      • 2. 清空表,删除表内的所有数据
      • 3. 创建临时表
      • 4. 创建外键约束,保证数据的完整性和一致性
      • 5. MySQL中6种常见的约束
    • 二、 数据库用户管理
      • 1. 新建用户
      • 2. 查看用户信息
      • 3. 重命名用户
      • 4. 删除用户
      • 5. 修改密码
        • (1)修改其他用户密码
        • (2)修改当前用户密码
      • 6. 忘记密码登录改密

一、数据表高级操作

1. 克隆表,将数据表的数据记录生成到新的表中

方法一:
create table test1 like test_table1;
通过like方法,复制test_table1表结构生成test1表
insert into test1 select * from test_table1;
将test_table1表中的数据复制到test1表中

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| info           |
| test_table1    |
+----------------+
2 rows in set (0.00 sec)

mysql> create table test1 like test_table1;
Query OK, 0 rows affected (0.02 sec)

mysql> desc test1;
+-----------+--------------+------+-----+--------------+-------+
| Field     | Type         | Null | Key | Default      | Extra |
+-----------+--------------+------+-----+--------------+-------+
| id        | int(11)      | NO   | PRI | NULL         |       |
| user_name | varchar(10)  | YES  | UNI | NULL         |       |
| score     | decimal(5,2) | YES  |     | NULL         |       |
| address   | varchar(50)  | YES  |     | 地址不详     |       |
+-----------+--------------+------+-----+--------------+-------+
4 rows in set (0.00 sec)

mysql> insert into test1 select * from test_table1;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from test1;
+----+-----------+-------+--------------+
| id | user_name | score | address      |
+----+-----------+-------+--------------+
|  1 | zhangsan  | 70.50 | 地址不详     |
+----+-----------+-------+--------------+
1 row in set (0.00 sec)

方法二:
create table test2 (select * from test1);
show create table test2\G
获取数据表的表结构、索引等信息
select * from test2;

mysql> create table test2  (select * from test1);
Query OK, 1 row affected (0.01 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> show create table test2\G
*************************** 1. row ***************************
       Table: test2
Create Table: CREATE TABLE "test2" (
  "id" int(11) NOT NULL,
  "user_name" varchar(10) DEFAULT NULL,
  "score" decimal(5,2) DEFAULT NULL,
  "address" varchar(50) DEFAULT '地址不详'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> select * from test2;
+----+-----------+-------+--------------+
| id | user_name | score | address      |
+----+-----------+-------+--------------+
|  1 | zhangsan  | 70.50 | 地址不详     |
+----+-----------+-------+--------------+
1 row in set (0.00 sec)

2. 清空表,删除表内的所有数据

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

mysql> delete from test_table1;
Query OK, 1 row affected (0.00 sec)

mysql> select * from test_table1;
Empty set (0.00 sec)

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

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

mysql> select * from test2;
Empty set (0.00 sec)

3. 创建临时表

create temporary table 表名 (字段1 数据类型,字段2 数据类型[,...] [,primary key (主键名)]);
临时表创建成功之后,使用show tables命令是看不到创建的临时表的,临时表会在连接退出后被销毁。如果在退出连接之前,也可以执行增删改查等操作,比如使用drop table语句手动直接删除临时表。

mysql> create temporary table test3 (
    -> id int(4) zerofill primary key auto_increment,
    -> name varchar(10) not null,
    -> cardid bigint(18) not null unique key,
    -> hobby varchar(50));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into test3 values(1,'zhangsan',112233445566778899,'running');
Query OK, 1 row affected (0.00 sec)

mysql> select * from test3;
+------+----------+--------------------+---------+
| id   | name     | cardid             | hobby   |
+------+----------+--------------------+---------+
| 0001 | zhangsan | 112233445566778899 | running |
+------+----------+--------------------+---------+
1 row in set (0.00 sec)

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| info           |
| test1          |
| test2          |
| test_table1    |
+----------------+
4 rows in set (0.00 sec)

mysql> quit
Bye

[root@localhost ~]# mysql -u root -p abc123
Enter password:
mysql> select * from test.test3;
ERROR 1146 (42S02): Table 'test.test3' doesn't exist

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

外键的定义:如果同一个属性字段x在表中是主键,而在表二中不是主键,则字段x称为表二的外键。
主键表和外键表的理解:
(1)以公共关键字做关键的表为主键表(父表、主表)
(2)以公共关键字做外键的表为外键表(从表、外表)
注意:与外键关联的主表的字段必须设置为主键,要求从表不能是临时表,主从表的字段具备相同的数据类型、字符长度和约束。

  1. 创建主表
    create table 主表名 (主键字段 数据类型,字段2 数据类型);
mysql> create table profession (pid int(4),proname varchar(50));
Query OK, 0 rows affected (0.01 sec)

mysql> desc profession;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| pid     | int(4)      | YES  |     | NULL    |       |
| proname | varchar(50) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
  1. 创建从表
    create table 从表名 (字段1 数据类型,字段2 数据类型,字段3 数据类型,外键字段 数据类型);
mysql> create table student (id int(4) primary key auto_increment,name varchar(10),age int(3),proid int(4));
Query OK, 0 rows affected (0.00 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(4)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10) | YES  |     | NULL    |                |
| age   | int(3)      | YES  |     | NULL    |                |
| proid | int(4)      | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
  1. 为主表添加一个主键约束,主键名建议以“PK_”开头
    alter table 主键表名 add [constraint PK_主键名] primary key (主键字段);
mysql> alter table profession add constraint PK_pid primary key (pid);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc profession;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| pid     | int(4)      | NO   | PRI | NULL    |       |
| proname | varchar(50) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
  1. 为从表添加外键,并将从表的外键字段和主表的主键字段建立外键关联。外键名建议以“FK_”开头
    alter table 外键表名 add [constraint FK_主键名] foreign key (外键字段) references 主键表名 (主键字段);
mysql> alter table student add constraint FK_pro foreign key (proid) references profession (pid);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(4)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10) | YES  |     | NULL    |                |
| age   | int(3)      | YES  |     | NULL    |                |
| proid | int(4)      | YES  | MUL | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
  1. 插入新的数据记录时,要先主表再从表
    主表赋值
mysql> insert into profession values(1,'数学');
Query OK, 1 row affected (0.00 sec)

mysql> insert into profession values(2,'英语');
Query OK, 1 row affected (0.00 sec)

mysql> select * from profession;
+-----+---------+
| pid | proname |
+-----+---------+
|   1 | 数学    |
|   2 | 英语    |
+-----+---------+
2 rows in set (0.00 sec)

从表赋值

mysql> insert into student values(1,'zhangsan',18,1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into student values(2,'lisi',19,1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into student values(3,'wangwu',20,2);
Query OK, 1 row affected (0.00 sec)

mysql> insert into student values(4,'zhaoliu',20,4);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ("test"."student", CONSTRAINT "FK_pro" FOREIGN KEY ("proid") REFERENCES "profession" ("pid"))
mysql> select * from student;
+----+----------+------+-------+
| id | name     | age  | proid |
+----+----------+------+-------+
|  1 | zhangsan |   18 |     1 |
|  2 | lisi     |   19 |     1 |
|  3 | wangwu   |   20 |     2 |
+----+----------+------+-------+
3 rows in set (0.00 sec)
  1. 删除数据记录时,要先从表再主表,也就是说删除主键表的记录时必须先删除其他与之关联的表中的记录。
mysql> delete from student where proid=1;
Query OK, 2 rows affected (0.01 sec)

mysql> delete from profession where pid=1;
Query OK, 1 row affected (0.00 sec)

mysql> delete from profession where pid=2;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails ("test"."student", CONSTRAINT "FK_pro" FOREIGN KEY ("proid") REFERENCES "profession" ("pid"))

mysql> select * from student;
+----+--------+------+-------+
| id | name   | age  | proid |
+----+--------+------+-------+
|  3 | wangwu |   20 |     2 |
+----+--------+------+-------+
1 row in set (0.00 sec)

mysql> select * from profession;
+-----+---------+
| pid | proname |
+-----+---------+
|   2 | 英语    |
+-----+---------+
1 row in set (0.00 sec)
  1. 查看和删除外键约束
mysql> mysql> show create table student;
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Table   | Create Table                                                                                                                                                                                                                                                
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| student | CREATE TABLE "student" (
  "id" int(4) NOT NULL AUTO_INCREMENT,
  "name" varchar(10) DEFAULT NULL,
  "age" int(3) DEFAULT NULL,
  "proid" int(4) DEFAULT NULL,
  PRIMARY KEY ("id"),
  KEY "FK_pro" ("proid"),
  CONSTRAINT "FK_pro" FOREIGN KEY ("proid") REFERENCES "profession" ("pid")
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 row in set (0.00 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(4)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10) | YES  |     | NULL    |                |
| age   | int(3)      | YES  |     | NULL    |                |
| proid | int(4)      | YES  | MUL | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> alter table student drop foreign key FK_pro;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table student drop key FK_pro;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(4)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(10) | YES  |     | NULL    |                |
| age   | int(3)      | YES  |     | NULL    |                |
| proid | int(4)      | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

5. MySQL中6种常见的约束

常见约束 说明
主键约束(primary key) 用于保证该字段的值具有唯一性并且非空
外键约束(foreign key) 用于限制两个表的关系,用于保证该字段的值必须来自于主表的关联列的值,在从表添加外键约束,用于引用主表中某些的值
非空约束(not null) 用于保证该字段的值不能为空
唯一性约束(unique [key index])
默认值约束(default) 用于保证该字段有默认值
自增约束(auto_increment) 用于保证该字段的值是上一条的+1值,也可以自定义值,下一条将在该值基础上+1。可以约束任何一个字段,该字段不一定是主键字段,但主键字段一定是自增字段,即primary_key要与auto_increment一起作用于同一个字段

二、 数据库用户管理

1. 新建用户

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

mysql> create user 'user1'@'localhost' identified by '123456';
Query OK, 0 rows affected (0.00 sec)

mysql> select password('123456');
+-------------------------------------------+
| password('123456')                        |
+-------------------------------------------+
| *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
+-------------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> create user 'user2'@'%' identified by password '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9';
Query OK, 0 rows affected, 1 warning (0.00 sec)

2. 查看用户信息

创建后的用户保存在mysql数据库的user表里

mysql> use mysql;
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> select user,authentication_string,host from user;
+---------------+-------------------------------------------+-----------+
| user          | authentication_string                     | host      |
+---------------+-------------------------------------------+-----------+
| root          | *6691484EA6B50DDDE1926A220DA01FA9E575C18A | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| root          | *6691484EA6B50DDDE1926A220DA01FA9E575C18A | %         |
| bbsuser       | *01A6717B58FF5C7EAFFF6CB7C96F7428EA65FE4C | %         |
| user1         | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | localhost |
| user2         | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | %         |
+---------------+-------------------------------------------+-----------+
7 rows in set (0.00 sec)

3. 重命名用户

rename user '旧用户名'@'旧来源地址' to '新用户名'@'新来源地址';
注:'新用户名'@'新来源地址'不可与已有账户冲突

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

mysql> select user,authentication_string,host from user;
+---------------+-------------------------------------------+-----------+
| user          | authentication_string                     | host      |
+---------------+-------------------------------------------+-----------+
| root          | *6691484EA6B50DDDE1926A220DA01FA9E575C18A | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| root          | *6691484EA6B50DDDE1926A220DA01FA9E575C18A | %         |
| bbsuser       | *01A6717B58FF5C7EAFFF6CB7C96F7428EA65FE4C | %         |
| zhangsan      | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | %         |
| user2         | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | %         |
+---------------+-------------------------------------------+-----------+
7 rows in set (0.00 sec)

mysql> rename user 'zhangsan'@'%' to 'user2'@'%';
ERROR 1396 (HY000): Operation RENAME USER failed for 'zhangsan'@'%'

4. 删除用户

drop user '用户名'@'来源地址';

mysql> drop user 'zhangsan'@'%'
    -> ;
Query OK, 0 rows affected (0.00 sec)

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

5. 修改密码

(1)修改其他用户密码

set password for '用户名'@'来源地址' = password('新密码');

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

mysql> select user,authentication_string,host from user;
+---------------+-------------------------------------------+-----------+
| user          | authentication_string                     | host      |
+---------------+-------------------------------------------+-----------+
| root          | *6691484EA6B50DDDE1926A220DA01FA9E575C18A | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| root          | *6691484EA6B50DDDE1926A220DA01FA9E575C18A | %         |
| bbsuser       | *01A6717B58FF5C7EAFFF6CB7C96F7428EA65FE4C | %         |
| user2         | *2A032F7C5BA932872F0F045E0CF6B53CF702F2C5 | %         |
+---------------+-------------------------------------------+-----------+
6 rows in set (0.00 sec)

(2)修改当前用户密码

set password = '新密码'

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

mysql> select user,authentication_string,host from user;
+---------------+-------------------------------------------+-----------+
| user          | authentication_string                     | host      |
+---------------+-------------------------------------------+-----------+
| root          |                                           | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| root          | *6691484EA6B50DDDE1926A220DA01FA9E575C18A | %         |
| bbsuser       | *01A6717B58FF5C7EAFFF6CB7C96F7428EA65FE4C | %         |
| user2         | *2A032F7C5BA932872F0F045E0CF6B53CF702F2C5 | %         |
+---------------+-------------------------------------------+-----------+
6 rows in set (0.00 sec)

6. 忘记密码登录改密

[root@localhost ~]# vim /etc/my.cnf

#在mysqld参数下插入以下内容,表示登录时跳过授权表。当忘记账号密码时可以使用该参数修改密码,但是要随用随关,重启mysql,不然服务器上会有很大的风险。
skip-grant-tables

[root@localhost ~]# systemctl restart mysqld
[root@localhost ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.20 Source distribution

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

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> use mysql;
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> update user set authentication_string=password('123456') where user='root';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 2  Changed: 1  Warnings: 1

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

mysql> select user,authentication_string,host from user;
+---------------+-------------------------------------------+-----------+
| user          | authentication_string                     | host      |
+---------------+-------------------------------------------+-----------+
| root          | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | localhost |
| mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| root          | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 | %         |
| bbsuser       | *01A6717B58FF5C7EAFFF6CB7C96F7428EA65FE4C | %         |
| user2         | *2A032F7C5BA932872F0F045E0CF6B53CF702F2C5 | %         |
+---------------+-------------------------------------------+-----------+
6 rows in set (0.00 sec)


这篇关于MySQL数据库操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程