mysql的理论和使用

mysql

1数据库原理

1.1数据的分类

在数据的获取和使用的过程中,我们可以根据数据的结构类型,将数据分成三类,分别是:结构化数 据,半结构化数据,非结构化数据。

结构化数据

结构化数据一般是指可以用二维表来逻辑表达实现的数据。是有固定的格式和有限长度的数据,可以用 关系型数据库表示和存储。 其特点是:数据以行为单位,一行数据表示一个实体信息,每一行数据的属性是相同的,存储在数据库 中;能够用统一的数据类型和结构加以表示;也能够用二维表结构来逻辑表达实现,包含属性和元组。

半结构化数据

半结构化数据就是介于完全结构化数据和完全无结构的数据之间的数据。 半结构化数据是结构化数据的一种形式,它并不符合关系型数据库或其它数据表的形式关联起来的数据 模型结构,但包含相关的标记,用来分隔语义元素及对记录和字段进行分层,数据的结构和内容混在一 起,没有明显的区分,因此,这种数据也被称为自描述结构的数据。 例如:HTML文档,JSON,XML和一些NoSQL数据库等就属于半结构化数据。

非结构化数据

顾名思义,就是没有固定结构的数据,这种数据没有固定格式和有限长度,无法用数据库二维逻辑表来 表现其结构,对于这类数据,我们一般进行整体存储。 典型的非结构化数据包括:二进制文件,音视频文件,位置信息等

1.2数据管理发展历史

如何有效管理大量数据,方法和手段都在随着计算机技术的发展而进步。 数据管理的发展经历了人工管理、文件系统和数据库系统三个发展阶段。

1.2.1数据管理的三个阶段

人工管理阶段

时间:20世纪50年代中期以前 特点:当时的计算机主要用于科学计算。外部存储设备只有磁带,打孔纸带等,也没有专业的数据管理 软件,所以在当时数据管理主要由人工完成。数据处理方式上基本是批处理。

文件系统管理阶段

时间:20世纪50年代后期至60年代中期 特点:随着时间的发展,计算机不仅用于科学计算,还用于信息管理,需要处理的数据量大增,数据存 储,检索和维护等问题迫切需要解决,同一时期,在硬件方面,出现了磁盘,磁鼓等可以直接连机存取 的设备,在此基础上,出现了基于文件系统的数据管理软件。使用磁盘文件的形式来管理数据,数据可 以在系统中长期保存,文件也有了各种各样的格式。在数据处理方式上可以批处理,也可以联机实时处 理。

数据库系统阶段

时间:20世纪60年代后期至今 特点:此时己经出现大容量的磁盘,且硬件价格开始下降。数据管理技术进入数据库系统阶段。数据库 系统克服了文件系统的缺陷,提供了对数据更高级、更有效的管理。这个阶段的程序和数据的联系是通 过数据库管理系统来实现的。数据库系统采用了复杂的结构化的数据模型,数据拥有高独立性,低冗余 度。

1.2.2文件管理系统的特点

优点 文件形式和格式多样化,数据可以长期保存,且数据具有一定的独立性,由文件系统进行管理

缺点 应用程序对接不方便,没有统一接口,也不支持对文件的并发访问,无安全控制功能,难以按用户视图 表示数据,数据间联系弱,数据冗余不可避免。

1.3数据库管理系统

1.3.1相关概念

数据库:Database

数据库是按照一定的数据结构来组织,存储和管理数据的仓库。 是一个长期存储在计算机内的、有组织的、可共享的、统一管理的大量数据的集合。

数据库管理系统:Database Management System(DBMS

数据库管理系统是一种操纵和管理数据库的大型软件,用于建立,使用和维护数据库,简称DBMS。 它对数据库进行统一的管理和控制,以保证数据库的安全性和完整性。

数据库管理员:Database Administrator(DBA

DBA是从事管理和维护数据库管理系统(DBMS)的相关工作人员的统称,属于运维工程师的一个分支, 主要负责业务数据库从设计、测试到部署交付的全生命周期管理。 DBA的核心目标是保证数据库管理系统的稳定性、安全性、完整性和高可用性能。

应用程序:Application

一个应用程序通常是指能够执行某种功能的软件程序。

1.3.2数据库管理系统特点

数据库管理系统中采用了复杂的数据模型表示数据结构,数据冗余小,易扩充,实现了数据共享。

具有较高的数据和程序独立性。数据库的独立性表现在物理独立性和逻辑独立性两个方面。

数据库管理系统为用户和应用程序提供了方便和统一的查询接口。

数据库管理系统的存在,使得数据可以和应用程序解耦。

数据库管理系统还具有并发控制,数据备份和恢复,完整性和安全性保障等功能。

1.3.3数据库管理系统基本功能

数据的定义:DBMS提供了数据定义语言DDL(DataDefinition Language),供用户定义数据库的 三级模式结构,两级映像以及完整性约束和保密限制等约束。DDL主要用于建立、修改数据库的库 结构。DDL所描述的库结构仅仅给出了数据库的框架,数据库的框架信息被存放在数据字典中。

  1. 数据操作:DBMS提供数据操作语言DML(DataManipulation Language),供用户实现对数据的 追加、删除、更新、查询等操作。

  2. 数据组织、存储与管理:DBMS要分类组织、存储和管理各种数据,包括数据字典、用户数据、存 取路径等,需确定以何种文件结构和存取方式在存储级上组织这些数据,如何实现数据之间的联 系。数据组织和存储的基本目标是提高存储空间利用率,选择合适的存取方法提高存取效率。

  3. 数据库的运行管理:数据库的运行管理功能是DBMS的运行控制、管理功能,包括多用户环境下的 并发控制、安全性检查和存取限制控制、完整性检查和执行、运行日志的组织管理、事务的管理和 自动恢复,即保证事务的原子性。这些功能保证了数据库系统的正常运行。

  4. 数据库的维护:这一部分包括数据库的数据载入、转换、转储、数据库的重组和重构以及性能监控 等功能,这些功能分别由各个使用程序来完成。

  5. 数据库的保护:数据库中的数据是信息社会的战略资源,所以数据的保护至关重要。DBMS对数据 库的保护通过4个方面来实现:数据库的恢复、数据库的并发控制、数据库的完整性控制、数据库安 全性控制。DBMS的其他保护功能还有系统缓冲区的管理以及数据存储的某些自适应调节机制等。

  6. 通信:DBMS具有与操作系统的联机处理、分时系统及远程作业输入的相关接口,负责处理数据的 传送。对网络环境下的数据库系统,还应该包括DBMS与网络中其他软件系统的通信功能以及数据 库之间的互操作功能。

1.3.4数据库管理系统

层次数据库

层次模型数据库系统是最早研制成功的数据库系统,这种数据库中的数据被组织成一个树状模型,这种 结构简单,但缺乏灵活性,各数据之间仅限于一对多的关系。 这种数据库最成功的典型代表是IBM的IMS(信息管理系统)。

网状数据库

网状数据库是采用网状原理和方法,以网状数据模型为基础建立的数据库。 网状数据模型是以记录类型为结点的网络结构,即一个结点可以有一个或多个下级结点,也可以有一个 或多个上级结点,两个结点之间甚至可以有多种联系,两个记录类型之间的值可以是多对多的联系。

关系型数据库管理系统

关系数据库管理系统:Relational DatabaseManagement System(RDBMS) 是指包括相互联系的逻辑组织和存取这些数据的一套程序(数据库管理系统软件)。关系数据库管理系 统就是管理关系数据库,并将数据逻辑组织的系统。 常见的关系型数据库管理系统有Oracle,MySQL,DB2,SQLServer等。 关系型数据库,是指采用了关系模型来组织数据的数据库,其以行和列的形式存储数据,以便于用户理 解,关系型数据库这一系列的行和列被称为表,一组表组成了数据库。用户通过查询来检索数据库中的 数据,而查询是一个用于限定数据库中某些区域的执行代码。关系模型可以简单理解为二维表格模型, 而一个关系型数据库就是由二维表及其之间的关系组成的一个数据组织。

关系型数据库中的相关概念

数据库: 数据库是一些关联表的集合。

数据表: 表是数据的矩阵。在一个数据库中的表看起来像一个简单的电子表格。

列(column): 一列(数据元素) 包含了相同类型的数据, 例如邮政编码的数据。

行(Row):一行(元组,或记录)是一组相关的数据,例如一条用户订阅的数据。

冗余:存储两倍数据,冗余降低了性能,但提高了数据的安全性。

主键(Primary key):主键是唯一的。一个数据表中只能包含一个主键。你可以使用主键来查询数 据。

外键:外键用于关联两个表。

复合键:复合键(组合键)将多个列作为一个索引键,一般用于复合索引。

索引:使用索引可快速访问数据库表中的特定信息。索引是对数据库表中一列或多列的值进行排序 的一种结构。类似于书籍的目录。

参照完整性: 参照的完整性要求关系中不允许引用不存在的实体。与实体完整性是关系模型必须满足 的完整性约束条件,目的是保证数据的一致性。

MySQL 为关系型数据库(

表头(header): 每一列的名称;

列(col): 具有相同数据类型的数据的集合;

行(row): 每一行用来描述某条记录的具体信息;

值(value): 行的具体信息, 每个值必须与该列的数据类型相同;

键(key): 键的值在当前列中具有唯一性。

1.4关系型数据库理论

1.4.1 E-R模型

R模型,全称为实体联系模型、实体关系模型或实体联系模式图(ERD:Entity-relationship model), 它提供不受任何DBMS约束的面向用户的表达方法,在数据库设计中被广泛用作数据建模的工具。

E-R图模型的组成是由实体,属性和联系三部份组成

1.4.2数据库的正规化分析(理论)

数据库规范化,又称数据库或资料库的正规化、标准化,是数据库设计中的一系列原理和技术,以减少 数据库中数据冗余,增进数据的一致性。设计关系数据库时,遵从不同的规范要求,设计出合理的关系 型数据库,不同的规范要求被称为不同范式,各种范式呈递次规范,越高的范式数据库冗余越小。

目前关系数据库有六种范式:第一范式(1NF)、第二范式(2NF)、第三范式(3NF)、巴德斯科范式 (BCNF)、第四范式(4NF)和第五范式(5NF,又称完美范式)。满足最低要求的范式是第一范式 (1NF)。在第一范式的基础上进一步满足更多规范要求的称为第二范式(2NF),其余范式以次类推。 一般数据库只需满足第三范式(3NF)即可。

第一范式1NF(确保每列保持原子性)

第一范式是最基本的范式。如果数据库表中的所有字段值都是不可分解的原子值,就说明该数据库表满 足了第一范式。 第一范式需要根据系统的实际需求来定。其核心是要保证数据表中的列里面没有重复值,即实体中的某 个属性不能有多个值或者不能有重复的属性,确保每一列的原子性。

核心要求:表中的每个字段都必须是不可再分的原子值

第二范式2NF(确保表中的每列都和主键相关)

第二范式在第一范式的基础之上更进一层。第二范式需要确保数据库表中的每一列都和主键相关,而不 能只与主键的某一部分相关(主要针对联合主键而言)。也就是说在一个数据库表中,一个表中只能保 存一种数据,不可以把多种数据保存在同一张数据库表中。

核心要求:所有非主键字段必须完全依赖于整个主键(不能只依赖主键的一部分)。

部分依赖:非主属性只依赖于主键中的某一部分。

第三范式3NF(确保每列都和主键列直接相关,而不是间接相关)

第三范式需要确保数据表中的每一列数据都和主键直接相关,而不能间接相关。 必须先满足第一范式才能满足第二范式,必须同时满足第一第二范式才能满足第三范式。

核心要求:非主键字段之间不能有依赖关系(即不能存在"传递依赖")。

传递依赖:A → B → C,则 C 传递依赖于 A。 所有非主属性必须直接依赖于主键

总结

范式 核心目标 关键规则

1NF 原子性 字段不可再分

2NF 消除部分依赖 非主属性必须完全依赖整个主键

3NF 消除传递依赖 非主属性之间不能相互依赖

2MySQL安装和基本使用

2.1MySQL 的特性

MySQL是基于开源协议发布的,可以免费使用,也可以基于源码进行二次开发。

MySQL使用标准SQL语言进行管理。

MySQL可以运行于多个系统上,具有跨平台特性,并且支持多种语言。

MySQL使用插件式存储引擎,不同的存储引擎,有着不同的功能和特性,使用者可以根据需要灵活 选择。

MySQL基于单进程,多线程的模式进行工作。 MySQL提供了大量的测试组件和诸多的扩展。

2.2 MySQL 命令类型

MySQL中的命令分为两类,分别是客户端命令和服务端命令。

客户端命令在本地执行。服务端命令发送到服务端执行,再返回执行结果到客户端上。

客户端命令和服务端命令,都是通过MySQL客户端工具进行输入输出。

查看所有客户端命令
复制代码
mysql> ?
For information about MySQL products and services, visit:
   http://www.mysql.com/
For developer information, including the MySQL Reference Manual, visit:
   http://dev.mysql.com/
To buy MySQL Enterprise support, training, or other products, visit:
   https://shop.mysql.com/
List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
edit     (\e) Edit command with $EDITOR.
ego       (\G) Send command to mysql server, display result vertically.
exit     (\q) Exit mysql. Same as quit.
go       (\g) Send command to mysql server.
help     (\h) Display this help.
nopager   (\n) Disable pager, print to stdout.
notee     (\t) Don't write into outfile.
pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.查看所有服务端命令
查看服务端命令具体项
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
system    (\!) Execute a system shell command.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog 
with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.
resetconnection(\x) Clean session context.
query_attributes Sets string parameters (name1 value1 name2 value2 ...) for the 
next query to pick up.
For server side help, type 'help contents'
查看所有服务端命令
复制代码
mysql> help contents
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the following
categories:
   Account Management
   Administration
   Components
   Compound Statements
   Contents
   Data Definition
   Data Manipulation
   Data Types
   Functions
   Geographic Features
   Help Metadata
   Language Structure
   Loadable Functions
   Plugins
   Prepared Statements
   Replication Statements
   Storage Engines
   Table Maintenance
   Transactions
   Utility
查看服务端命令具体项
复制代码
mysql> help Administration
You asked for help about help category: "Administration"
For more information, type 'help <item>', where <item> is one of the following
topics:
   BINLOG
   CACHE INDEX
   FLUSH
   HELP COMMAND   KILL
   LOAD INDEX
   RESET
   RESET PERSIST
   RESTART
   SET
   SET CHARACTER SET
   SET CHARSET
   SET NAMES
   SHOW
   SHOW BINARY LOGS
   SHOW BINLOG EVENTS
   SHOW CHARACTER SET
   SHOW COLLATION
   SHOW COLUMNS
   SHOW CREATE DATABASE
   SHOW CREATE EVENT
   SHOW CREATE FUNCTION
   SHOW CREATE PROCEDURE
   SHOW CREATE SCHEMA
   SHOW CREATE TABLE
   SHOW CREATE TRIGGER
   SHOW CREATE USER
   SHOW CREATE VIEW
   SHOW DATABASES
   SHOW ENGINE
   SHOW ENGINES
   SHOW ERRORS
   SHOW EVENTS
   SHOW FIELDS
   SHOW FUNCTION CODE
   SHOW FUNCTION STATUS
   SHOW GRANTS
   SHOW INDEX
   SHOW MASTER LOGS
   SHOW MASTER STATUS
   SHOW OPEN TABLES
   SHOW PLUGINS
   SHOW PRIVILEGES
   SHOW PROCEDURE CODE
   SHOW PROCEDURE STATUS
   SHOW PROCESSLIST
   SHOW PROFILE
   SHOW PROFILES
   SHOW RELAYLOG EVENTS
   SHOW REPLICA STATUS
   SHOW REPLICAS
   SHOW SCHEMAS
   SHOW SLAVE HOSTS
   SHOW SLAVE STATUS
   SHOW STATUS
   SHOW TABLE STATUS
   SHOW TABLES
   SHOW TRIGGERS
   SHOW VARIABLES
   SHOW WARNINGS

2.3MySQL客户端使用

2.3.1MySQL客户端使用
格式:
复制代码
[root@localhost ~]# mysql --help
Usage: mysql [OPTIONS] [database]
#常用选项
-V|--version #显示客户端版本
-u|--user=name #指定远程连接用户名
-p|--password[=name] #指定密码,默认为空
-h|--host=host #指定服务端主机
-P|--port=port #指定端口,默认3306
-S|--socket=name #指定连接时使用的socket文件,该文件在服务端启动后生成
-D|--database=db #指定数据库
-H|--html #以html格式输出
-X|--xml #以xml格式输出
-t|--table #以table格式输出,默认项
-E|--vertical #垂直显示执行结果
-v|--verbose #显示详细信息,配合-t选项
-C|--compress #启用压缩
-G|--named-commands #启用长命令
-e|--execute=sql #执行完就退出,非交互式运行
-prompt=name #修改命令提示符
--line-numbers #输出行号范例:
--print-defaults #打印参数列表,放在最前面
--connect-timeout=N #连接超时时长,单位S
--max-allowed-packet=N #一次查交互发送或反回数据的大小,默认16MB,最大值为1GB,最小值
为4096字节
范例:
复制代码
#免密登录
[root@localhost ~]# mysql -uroot -pHuawei@123
mysql> alter user root@localhost identified by '';        #将mysql root账号密码设置
为空
mysql> quit                                               #退出mysql
#显示版本
[root@localhost ~]# mysql -V
mysql Ver 8.0.26 for Linux on x86_64 (Source distribution)
#指定用户名,主机,端口
[root@localhost ~]# mysql -uroot -h127.0.0.1 -P3306
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
#使用主机名
[root@localhost ~]# mysql --user=root --host=localhost --port=3306
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 23
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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>
#默认使用root连接,密码为空
[root@localhost ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 24
Server version: 8.0.26 Source distribution 
范例:执行完退出,非交互式执行
Copyright (c) 2000, 2021, 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.
#打印参数列表,并不连接服务端,--print-defaults要放在第一个
[root@localhost ~]# mysql --print-defaults -uroot -hlocalhost --connect-timeout=2
mysql would have been started with the following arguments:
-uroot -hlocalhost --connect-timeout=2
#以html格式显示输出
[root@localhost ~]# mysql -H
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 25
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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 version();
<TABLE BORDER=1><TR><TH>version()</TH></TR><TR><TD>8.0.26</TD></TR></TABLE>1 row 
in set (0.00 sec)
范例:执行完退出,非交互式执行
复制代码
#环境准备
[root@localhost ~]# vim /root/test.sql
show databases;
#执行客户端命令
[root@localhost ~]# mysql -e "source /root/test.sql"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
#管道执行
[root@localhost ~]# cat test.sql | mysql
Database
information_schema
mysql范例:修改提示符
范例:指定数据库
performance_schema
sys
#标准输入重定向执行
[root@localhost ~]# mysql -uroot < test.sql
Database
information_schema
mysql
performance_schema
sys
#以table格式输出
[root@localhost ~]# mysql -e "show databases;"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
#垂直显示
[root@localhost ~]# mysql -e "show databases;" -E
*************************** 1. row ***************************
Database: information_schema
*************************** 2. row ***************************
Database: mysql
*************************** 3. row ***************************
Database: performance_schema
*************************** 4. row ***************************
Database: sys
范例:修改提示符
复制代码
[root@localhost ~]# mysql --prompt=[test]
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 37
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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.
[test]
范例:指定数据库
复制代码
#默认
[root@localhost ~]# mysql 
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 38
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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               |
+--------------------+
4 rows in set (0.00 sec)
mysql>
#指定数据库
[root@localhost ~]# mysql information_schema
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 41
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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 DATABASE();
+--------------------+
| DATABASE()         |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.01 sec)
mysql>

2...1.3.2 MySQL客户端常用命令

复制代码
mysql> ?
For information about MySQL products and services, visit:
   http://www.mysql.com/
For developer information, including the MySQL Reference Manual, visit:
   http://dev.mysql.com/
To buy MySQL Enterprise support, training, or other products, visit:
   https://shop.mysql.com/
List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
edit     (\e) Edit command with $EDITOR.
ego       (\G) Send command to mysql server, display result vertically.
exit     (\q) Exit mysql. Same as quit.
go       (\g) Send command to mysql server.
help     (\h) Display this help.
nopager   (\n) Disable pager, print to stdout.
notee     (\t) Don't write into outfile.
pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print     (\p) Print current command.
prompt   (\R) Change your mysql prompt.
quit     (\q) Quit mysql.
rehash   (\#) Rebuild completion hash.
source   (\.) Execute an SQL script file. Takes a file name as an argument.
status   (\s) Get status information from the server.
system   (\!) Execute a system shell command.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog 
with multi-byte charsets.
warnings (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.
resetconnection(\x) Clean session context.
query_attributes Sets string parameters (name1 value1 name2 value2 ...) for the 
next query to pick up.
For server side help, type 'help contents'
范例:显示当前数据库
复制代码
#显示当前数据库
mysql> \s
--------------
mysql Ver 8.0.26 for Linux on x86_64 (Source distribution)
 
Connection id:          8                              #连接ID
Current database:                                      #当前使用的数据库范例:切换数据库
范例:调用系统命令
范例:修改提示符
在配置文件中修改提示符
Current user:           root@localhost                 #连接使用的用户名
SSL:                    Not in use                     #是否使用ssl
Current pager:         stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         8.0.26 Source distribution     #版本
Protocol version:       10                             #协议版本
Connection:             Localhost via UNIX socket
Server characterset:   utf8mb4                        #服务器编码
Db     characterset:   utf8mb4                        #数据库编码
Client characterset:   utf8mb4                        #客户端编码
Conn. characterset:   utf8mb4
UNIX socket:           /var/lib/mysql/mysql.sock      #连接使用的socket文件
Binary data as:         Hexadecimal
Uptime:                 28 min 46 sec                  #服务器运行时长
Threads: 2 Questions: 6  Slow queries: 0 Opens: 117  Flush tables: 3  Open 
tables: 36 Queries per second avg: 0.003  
范例:切换数据库
复制代码
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>
范例:调用系统命令
复制代码
mysql> \! hostname          #查看宿主机主机名,!号后面有空格
localhost.localdomain
mysql> \! clear             #清屏
范例:修改提示符
复制代码
mysql> prompt [\h--\D]
PROMPT set to '[\h--\D]'
[localhost--Mon Sep 15 22:09:09 2025]
[localhost--Mon Sep 15 22:10:01 2025]\R abcd
PROMPT set to 'abcd'
abcd
abcd

在配置文件中修改提示符

复制代码
[root@localhost ~]# vim /etc/my.cnf.d/client.cnf
[client]
prompt=(\\u@\\h) [\\d]>\\

[root@localhost ~]# mysql         #验证效果 
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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.
(root@localhost) [(none)]>       #效果

提示符中可用的变量,全部可用的替换符用man mysql查看

复制代码
\C #计数器
\D #年月日时分秒
\d #当前使用的数据库
\h #服务器主机名
\l  #命令分隔符,默认;
\m #当前时间,分钟
\n #换行
\O #月份,以英文显示
\o #月份,数字显示
\P #pm/am
\R #小时,24小时制
\r #小时,12小时制
\S #分号
\s #秒,数字显示
\t #tab键
\U #客户端用户名和主机
\u #客户端用户名
\v #服务端版本
\w #星期几,英文显示
\Y #年份,四位,数字显示
\y #年份,两位,数字显示
范例:执行SQL脚本
复制代码
[root@localhost ~]# vim test.sql
show databases;
mysql> \. /root/test.sql
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
4 rows in set (0.00 sec)
范例:重连
复制代码
[root@localhost ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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> \r
Connection id:    20
Current database: *** NONE ***
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> \r
Connection id:    21
Current database: mysql
mysql>
范例:往文件中保存输出结果
复制代码
mysql> tee db.txt                 #设置写到文件db.txt
Logging to file 'db.txt'
mysql> select version();          #执行SQL语句
+-----------+
| version() |
+-----------+
| 8.0.26   |
+-----------+范例:自定义
1 row in set (0.00 sec)
mysql> \t                        #设置不写文件
Outfile disabled.
mysql> show databases;          #执行SQL语句
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
4 rows in set (0.00 sec)
mysql> quit                     #退出
Bye
[root@localhost ~]# cat db.txt         #只记录了\t之前的命令
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.26   |
+-----------+
1 row in set (0.00 sec)
mysql> \t
[root@localhost ~]#
范例:自定义
复制代码
两条查询语句,默认用;分隔
mysql> select version();show databases;
+-----------+
| version() |
+-----------+
| 8.0.26   |
+-----------+
1 row in set (0.00 sec)
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
4 rows in set (0.01 sec)
#设置$分隔
mysql> \d $范例:发送语句到服务端
mysql> select version()$show databases$
+-----------+
| version() |
+-----------+
| 8.0.26   |
+-----------+
1 row in set (0.01 sec)
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
4 rows in set (0.00 sec)
范例:发送语句到服务端
复制代码
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.26   |
+-----------+
1 row in set (0.01 sec)
mysql> select version()\g
+-----------+
| version() |
+-----------+
| 8.0.26   |
+-----------+
1 row in set (0.00 sec)
mysql> select version()\G
*************************** 1. row ***************************
version(): 8.0.26
1 row in set (0.00 sec)
#开启长命令格式
[root@localhost ~]# mysql --named-commands
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 26
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, 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.范例:只输出不执行
 
2.4.4.3 mysqladmin工具 
mysqladmin也是用于管理mysql服务的本地工具
格式
mysql> select version()        #这里要断句
    -> go
+-----------+
| version() |
+-----------+
| 8.0.26   |
+-----------+
1 row in set (0.00 sec)
mysql> select version()       #这里要断句
    -> ego
*************************** 1. row ***************************
version(): 8.0.26
1 row in set (0.00 sec)
范例:只输出不执行
复制代码
mysql> select version()\p
--------------
select version()
--------------

2.4 mysqladmin

mysqladmin也是用于管理mysql服务的本地工具u

格式
复制代码
[root@localhost ~]# mysqladmin --help
mysqladmin Ver 8.0.26 for Linux on x86_64 (Source distribution)
Copyright (c) 2000, 2021, 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.
Administration program for the mysqld daemon.
Usage: mysqladmin [OPTIONS] command command....
  --bind-address=name IP address to bind to.
  -c, --count=#       Number of iterations to make. This works with -i         #
总共执行多少次,配合-i选项使用
                     (--sleep) only.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       This is a non-debug version. Catch this and exit.
  --debug-info       This is a non-debug version. Catch this and exit.
  -f, --force         Don't ask for confirmation on drop database; with
                     multiple commands, continue even if an error occurs.
  -C, --compress     Use compression in server/client protocol.           #启用压
缩
  --character-sets-dir=name
                     Directory for character set files.  --default-character-set=name
                     Set the default character set.
  -?, --help         Display this help and exit.            #显示帮助信息
  -h, --host=name     Connect to host.                       #指定服务器地址
  -b, --no-beep       Turn off beep on error.
  -p, --password[=name]                                      #指定连接服务器的密码
                     Password to use when connecting to server. If password is
                     not given it's asked from the tty.
  -P, --port=#       Port number to use for connection or 0 for default to, in   
#指定服务器端口,默认3306
                     order of preference, my.cnf, $MYSQL_TCP_PORT,
                     /etc/services, built-in default (3306).
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,     
  #指定连接方式(tcp\socket\pipe\memory)
                     memory).
  -r, --relative     Show difference between current and previous values when
                     used with -i. Currently only works with extended-status.
  -s, --silent       Silently exit if one can't connect to server.       #如果无
法连接,则静默退出
  -S, --socket=name   The socket file to use for connection.               #指定连
接时使用socket文件
  -i, --sleep=#       Execute commands repeatedly with a sleep between.   #持续执
行命令,间隔N秒执行一次
  --ssl-mode=name     SSL connection mode.
  --ssl-ca=name       CA file in PEM format.
  --ssl-capath=name   CA directory.
  --ssl-cert=name     X509 cert in PEM format.
  --ssl-cipher=name   SSL cipher to use.
  --ssl-key=name     X509 key in PEM format.
  --ssl-crl=name     Certificate revocation list.
  --ssl-crlpath=name Certificate revocation list path.
  --tls-version=name TLS version to use, permitted values are: TLSv1, TLSv1.1,
                     TLSv1.2, TLSv1.3
  --ssl-fips-mode=name
                     SSL FIPS mode (applies only for OpenSSL); permitted
                     values are: OFF, ON, STRICT
  --tls-ciphersuites=name
                     TLS v1.3 cipher to use.
  --server-public-key-path=name
                     File path to the server public RSA key in PEM format.
  --get-server-public-key
                     Get server public key
  -u, --user=name     User for login if not current user.             #指定用户名
  -v, --verbose       Write more information.              
  -V, --version       Output version information and exit.             #显示客户端
版本
  -E, --vertical     Print output vertically. Is similar to --relative, but
                     prints output vertically.
  -w, --wait[=#]     Wait and retry if connection is down.           #如果连接失
败,是否等待重试,如果指定了具体数字,则表示重试几次
  --connect-timeout=#                                         #指定连接超时时长
  --shutdown-timeout=#                                         #指定关机超时时长
  --plugin-dir=name   Directory for client-side plugins.       #客户端插件目录
  --default-auth=name Default authentication client-side plugin to use.
  --enable-cleartext-plugin
                     Enable/disable the clear text authentication plugin.  --show-warnings     Show warnings after execution
  --compression-algorithms=name
                     Use compression algorithm in server/client protocol.
                     Valid values are any combination of
                      'zstd','zlib','uncompressed'.
  --zstd-compression-level=#
                     Use this compression level in the client/server protocol,
                      in case --compression-algorithms=zstd. Valid range is
                     between 1 and 22, inclusive. Default is 3.
Variables (--variable-name=value)
and boolean options {FALSE|TRUE} Value (after reading options)
--------------------------------- ----------------------------------------
bind-address                     (No default value)
count                             0
force                             FALSE
compress                         FALSE
character-sets-dir               (No default value)
default-character-set             auto
host                             (No default value)
no-beep                           FALSE
port                              0
relative                         FALSE
socket                           (No default value)
sleep                             0
ssl-ca                           (No default value)
ssl-capath                       (No default value)
ssl-cert                         (No default value)
ssl-cipher                       (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
tls-version                       (No default value)
tls-ciphersuites                 (No default value)
server-public-key-path           (No default value)
get-server-public-key             FALSE
user                             (No default value)
verbose                           FALSE
vertical                         FALSE
connect-timeout                   43200
shutdown-timeout                  3600
plugin-dir                       (No default value)
default-auth                     (No default value)
enable-cleartext-plugin           FALSE
show-warnings                     FALSE
compression-algorithms           (No default value)
zstd-compression-level            3
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf
The following groups are read: mysqladmin client
The following options may be given as the first argument:
--print-defaults       Print the program argument list and exit.            #显示
运行参数
--no-defaults           Don't read default options from any option file,
                       except for login file. 范例:显示版本信息
--defaults-file=#       Only read default options from the given file #.     #从
指定文件中读取选项
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                       Also read groups with concat(group, suffix)
--login-path=#         Read this path from the login file.
Where command is a one or more of: (Commands may be shortened)
 create databasename   Create a new database                  #创建新的数据库
 debug                 Instruct server to write debug information to log      #
开启调试模式,将调试信息写入log
 drop databasename     Delete a database and all its tables       #删除指定数据库
 extended-status       Gives an extended status message from the server       #
显示扩展状态
 flush-hosts           Flush all cached hosts                 #刷新所有缓存的主机
 flush-logs           Flush all logs                         #刷新所有日志    
 flush-status         Clear status variables                 #刷新状态变量
 flush-tables         Flush all tables                       #刷新所有表,会强制关
闭已打开的表
 flush-threads         Flush the thread cache                 #刷新线程缓存
 flush-privileges     Reload grant tables (same as reload)   #刷新访问权限       
         
  kill id,id,...       Kill mysql threads
 password [new-password] Change old password to new-password in current format   
 #修改密码
  ping                 Check if mysqld is alive               #心跳检测
 processlist           Show list of active threads in server  #显示活动线程列表
 reload               Reload grant tables                    #刷新授权信息
 refresh               Flush all tables and close and open logfiles   #刷新所有数
据库表,重新打开日志文件
 shutdown             Take server down                       #关闭服务
 status               Gives a short status message from the server      #简短显
示服务端状态
 start-replica         Start replication                     
 start-slave           Deprecated: use start-replica instead            #开启主从
同步
 stop-replica         Stop replication       
 stop-slave           Deprecated: use stop-replica instead             #停止主从
同步
 variables             Prints variables available                       #显示服务
端所有变量
 version               Get version info from server                     #显示客户
端和服务端版本
范例:显示版本信息
复制代码
#客户端版本
[root@localhost ~]# mysqladmin -V            
mysqladmin Ver 8.0.26 for Linux on x86_64 (Source distribution)
#客户端和服务端版本信息
[root@localhost ~]# mysqladmin version
mysqladmin Ver 8.0.26 for Linux on x86_64 (Source distribution)
Copyright (c) 2000, 2021, 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.
Server version          8.0.26
Protocol version        10
Connection             Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 1 hour 44 min 34 sec
Threads: 4 Questions: 189 Slow queries: 0 Opens: 287 Flush tables: 3 Open 
tables: 206 Queries per second avg: 0.030
范例:显示状态信息
复制代码
[root@localhost ~]# mysqladmin status
Uptime: 6352 Threads: 4 Questions: 191 Slow queries: 0 Opens: 287 Flush 
tables: 3 Open tables: 206 Queries per second avg: 0.030
范例:设置连接超时
复制代码
[root@localhost ~]# mysqladmin -h1.2.3.4 --connect-timeout=2 ping
mysqladmin: connect to server at '1.2.3.4' failed
error: 'Can't connect to MySQL server on '1.2.3.4:3306' (110)'
Check that mysqld is running on 1.2.3.4 and that the port is 3306.
You can check this by doing 'telnet 1.2.3.4 3306'
[root@localhost ~]# echo $?
1
#静默退出,不输出错误信息
[root@localhost ~]# mysqladmin -h1.2.3.4 --connect-timeout=2 -s ping
[root@localhost ~]# echo $?
1
范例:持续执行
复制代码
#每秒执行一次ping命令,一直执行下去
[root@localhost ~]# mysqladmin -i 1 ping
mysqld is alive
mysqld is alive
mysqld is alive
......
#每秒执行一次ping命令,总共执行3次
[root@localhost ~]# mysqladmin -i 1 -c 3 ping
mysqld is alive
mysqld is alive
mysqld is alive
范例:关闭服务
复制代码
#mysqladmin只能关闭服务,不能启动服务
[root@localhost ~]# mysqladmin shutdown
[root@localhost ~]# mysqladmin ping
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket 
'/var/lib/mysql/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/var/lib/mysql/mysql.sock' 
exists!
[root@localhost ~]# echo $?
1
[root@localhost ~]# systemctl start mysqld
范例:创建数据库和删除数据库
复制代码
#创建
[root@localhost ~]# mysqladmin create mysqladmin-db1
[root@localhost ~]# mysqladmin create mysqladmin-db2
[root@localhost ~]# mysql -e 'show databases'
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql             |
| mysqladmin-db1     |
| mysqladmin-db2     |
| performance_schema |
| sys               |
+--------------------+
#删除
[root@localhost ~]# mysqladmin drop mysqladmin-db1
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.
Do you really want to drop the 'mysqladmin-db1' database [y/N] y      #回答y确认
Database "mysqladmin-db1" dropped
[root@localhost ~]# mysqladmin -f drop mysqladmin-db2     #强制删除,不需要确认
Database "mysqladmin-db2" dropped
[root@localhost ~]# mysql -e 'show databases'     #验证mysqladmin-db1和mysqladmindb2已经删除
+--------------------+
|
 Database           |
+--------------------+
| information_schema |
| mysql             |
| performance_schema |
| sys               |
+--------------------+
[root@localhost ~]#
范例:修改连接密码
复制代码
#旧密码为空,root用户,localhost主机连接
[root@localhost ~]# mysqladmin password 123456             #设置密码为123456
mysqladmin: [Warning] Using a password on the command line interface can be 
insecure.
Warning: Since password will be sent to server in plain text, use ssl connection 
to ensure password safety.
[root@localhost ~]# mysqladmin ping                 #不使用密码不行
mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'root'@'localhost' (using password: NO)'
[root@localhost ~]# mysqladmin -uroot -hlocalhost -p123456 ping       #使用密码
123456
mysqladmin: [Warning] Using a password on the command line interface can be 
insecure.
mysqld is alive
#用旧密码修改新密码
[root@localhost ~]# mysqladmin -uroot -p123456 -hlocalhost password abcde     #
更改密码为abcde
mysqladmin: [Warning] Using a password on the command line interface can be 
insecure.
Warning: Since password will be sent to server in plain text, use ssl connection 
to ensure password safety.
[root@localhost ~]# mysqladmin -uroot -p123456 -hlocalhost ping         #使用原密码
测试不行
mysqladmin: [Warning] Using a password on the command line interface can be 
insecure.
mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'root'@'localhost' (using password: YES)'
[root@localhost ~]# mysqladmin -uroot -pabcde -hlocalhost ping       #使用新密码测
试
mysqladmin: [Warning] Using a password on the command line interface can be 
insecure.
mysqld is alive

2.5 mycli 工具

MyCLI是基于Python开发的MySQL的命令行工具,具有自动完成和语法突出显示功能

复制代码
[root@localhost ~]# yum install -y python39
[root@localhost ~]# pip3.9 config set global.index-url 
https://pypi.tuna.tsinghua.edu.cn/simple
Writing to /root/.config/pip/pip.conf
[root@localhost ~]# pip3 install mycli==1.2.0
#使用
[root@localhost ~]# mycli -uroot -pabcde
Connecting to socket /var/lib/mysql/mysql.sock, owned by user mysql
MySQL
mycli 1.38.4
Home: http://mycli.net
Bug tracker: https://github.com/dbcli/mycli/issues
Thanks to the contributor - Artem Bezsmertnyi
MySQL root@(none):(none)>
相关推荐
ZC跨境爬虫2 小时前
3D地球卫星轨道可视化平台开发 Day15(添加卫星系列模糊搜索功能)
前端·数据库·3d·交互·数据可视化
tjc199010052 小时前
SQL中如何处理GROUP BY的不可排序问题_ORDERBY与聚合
jvm·数据库·python
JoshRen2 小时前
Python使用PyMySQL操作MySQL完整指南
数据库·python·mysql
2601_949816222 小时前
MySQL 启动失败 (code=exited, status=1FAILURE) 异常解决方案
数据库·mysql
HHHHH1010HHHHH2 小时前
CSS定位如何实现多行文字垂直居中_通过绝对定位模拟表格
jvm·数据库·python
riNt PTIP2 小时前
Ubuntu 系统下安装 Nginx
数据库·nginx·ubuntu
麻辣大虾2 小时前
SQL语言五大分类
数据库·sql·mysql
chenxu98b2 小时前
redis info 详解
数据库·redis·缓存
qq_413847402 小时前
Redis怎样设计企业级备份策略_结合全量RDB与增量AOF实现多级数据保护
jvm·数据库·python