文章目录
- [3. mysql - MySQL 命令行客户端](#3. mysql - MySQL 命令行客户端)
-
- [3.4 mysql 客户端命令](#3.4 mysql 客户端命令)
- [3.5 从.sql文件执行 SQL 语句](#3.5 从.sql文件执行 SQL 语句)
-
- [3.5.1 使用source命令导入](#3.5.1 使用source命令导入)
- [3.5.2 使用mysql客户端导入](#3.5.2 使用mysql客户端导入)
3. mysql - MySQL 命令行客户端
3.4 mysql 客户端命令
使用
mysql客户端程序连接到数据库服务器之后,可以发送SQL语句到服务器执行,并以 ";"(分号)、\g或\G结束
注意:
;与\g结束表示以表格形式展示结果\G结束表示以行形式展示结果(有的时候,一些结果一行显示不下就会出现乱码,这个时候适合使用这个来显示)- 如果当前已经输入了一部分
SQL语句想重新输入可以输入Control+C中断当前输入
在当前模式下,mysql还有一组自己的命令,可以输入 help or \h 查看命令列表
一些常用的:
connect (\r):重新连接服务器
status (\s):查看当前服务器的状态
delimiter (\d):重新指定SQL语句的结束标识符
- 例如:
delimiter /- 之后需要使用的
;就变成了/
exit (\q):退出MySQL客户端程序
quit (\q):退出MySQL客户端程序
tee (\T):把所有的执行结果储存到执行的文件中
- 例如:
tee /root/test1.txt,执行后接下来的操作都会自动保存在/root/test1.txt文件里面(这个文件没有就会自动创建一个)
notee (\t):执行结果不再写入文件,这个无参数
prompt (\R):修改提示符
- 比如默认:
mysql>- 修改后:
prompt lx >>>- 展示结果:
lx >>>
source (\.):加载并执行指定的.sql脚本
system (\!):执行系统命令,非常危险(如果权限配置不当,那么别人可以给你做一些坏事)
warnings (\W):显示告警信息
nowarning (\w):不显示告警信息
mysql
mysql> help
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.
ssl_session_data_print Serializes the current SSL session data to stdout or
file
For server side help, type 'help contents'
使用help contents命令可以查看关于MySQL数据库使用的具体帮助,包括用户管理、SQL语法、数据类型、组件等相关内容列表。
mysql
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
通过help contents中的具体条目查看介绍,例如:help Data Types
mysql
mysql> help Data Types # 这里说明要查看关于数据类型的帮助信息
You asked for help about help category: "Data Types"
For more information, type 'help <item>', where <item> is one of the following
topics:
AUTO_INCREMENT
BIGINT
BINARY
BIT
BLOB
BLOB DATA TYPE
BOOLEAN
CHAR
CHAR BYTE
DATE
DATETIME
DEC
DECIMAL
DOUBLE
DOUBLE PRECISION
ENUM
FLOAT
INT
INTEGER
LONGBLOB
LONGTEXT
MEDIUMBLOB
MEDIUMINT
MEDIUMTEXT
SET DATA TYPE
SMALLINT
TEXT
TIME
TIMESTAMP
TINYBLOB
TINYINT
TINYTEXT
VARBINARY
VARCHAR
YEAR DATA TYPE
继续输入help 具体的条目 查看关于此条目的详细说明,例如:help BIT
mysql
mysql> help BIT # 以下显示关于BIT数据类形的具体描述
Name: 'BIT'
Description:
BIT[(M)]
A bit-value type. M indicates the number of bits per value, from 1 to
64. The default is 1 if M is omitted.
URL: https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
3.5 从.sql文件执行 SQL 语句
3.5.1 使用source命令导入
有时候我们需要从
.sql文件执行一些SQL语句,比如要把一个数据库从一台服务器A复制到另一台服务器B上,那么可以先从服务器A导出数据到.sql文件,然后在服务器B执行这个.sql文件。使用场景:开发环境--->测试环境--->生产环境
在上一小节,用
help命令查看命令列表,可以看到有一个source命令如下所示:
mysql
mysql> help
# 省略...
source (\.) Execute an SQL script file. Takes a file name as an argument.
# 省略...
下面我们演示一下source命令的使用方法
- 准备要执行的
.sql文件,名为test_db.sql,内容如下:
mysql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP DATABASE IF EXISTS `test_db`;
CREATE DATABASE `test_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
USE `test_db`;
-- ----------------------------
-- Table structure for classes
-- ----------------------------
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`desc` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of classes
-- ----------------------------
INSERT INTO `classes` VALUES (1, '计算机系2019级1班', '学习了计算机原理、C和Java语言、数据结构和算法');
INSERT INTO `classes` VALUES (2, '中文系2019级3班', '学习了中国传统文学');
INSERT INTO `classes` VALUES (3, '自动化2019级5班', '学习了机械自动化');
-- ----------------------------
-- Table structure for course
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES (1, 'Java');
INSERT INTO `course` VALUES (2, '中国传统文化');
INSERT INTO `course` VALUES (3, '计算机原理');
INSERT INTO `course` VALUES (4, '语文');
INSERT INTO `course` VALUES (5, '高阶数学');
INSERT INTO `course` VALUES (6, '英文');
-- ----------------------------
-- Table structure for score
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
`score` decimal(3, 1) NULL DEFAULT NULL,
`student_id` int(11) NULL DEFAULT NULL,
`course_id` int(11) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of score
-- ----------------------------
INSERT INTO `score` VALUES (70.5, 1, 1);
INSERT INTO `score` VALUES (98.5, 1, 3);
INSERT INTO `score` VALUES (33.0, 1, 5);
INSERT INTO `score` VALUES (98.0, 1, 6);
INSERT INTO `score` VALUES (60.0, 2, 1);
INSERT INTO `score` VALUES (59.5, 2, 5);
INSERT INTO `score` VALUES (33.0, 3, 1);
INSERT INTO `score` VALUES (68.0, 3, 3);
INSERT INTO `score` VALUES (99.0, 3, 5);
INSERT INTO `score` VALUES (67.0, 4, 1);
INSERT INTO `score` VALUES (23.0, 4, 3);
INSERT INTO `score` VALUES (56.0, 4, 5);
INSERT INTO `score` VALUES (72.0, 4, 6);
INSERT INTO `score` VALUES (81.0, 5, 1);
INSERT INTO `score` VALUES (37.0, 5, 5);
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) PRIMARY KEY AUTO_INCREMENT,
`sn` int(11) NOT NULL COMMENT '学号',
`name` varchar(20) NOT NULL COMMENT '姓名',
`mail` varchar(20) COMMENT 'QQ邮箱'
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, 50001, '张三', 'zs@bit.com');
INSERT INTO `student` VALUES (2, 50002, '李四', 'ls@bit.com');
INSERT INTO `student` VALUES (3, 50003, '王五', 'ww@bit.com');
INSERT INTO `student` VALUES (4, 50004, '赵六', 'zl@bit.com');
INSERT INTO `student` VALUES (5, 50005, '钱七', 'qq@bit.com');
SET FOREIGN_KEY_CHECKS = 1;
- 确定
.sql文件的绝对路径:/root/108_class/9_test_db.sql
mysql
root@iZuf68hz06p6s2809gl3i1Z:~/108_class# ll /root/108_class/9_test_db.sql
-rw-r--r-- 1 root root 3806 Feb 2 2024 /root/108_class/9_test_db.sql
root@iZuf68hz06p6s2809gl3i1Z:~/108_class#
- 连接数据库查看已有数据库
mysql
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| db1 |
| helloworld |
| information_schema |
| mysql |
| performance_schema |
| scott |
| sys |
| test_db | # 其实就是这个,我之前上传了
+--------------------+
8 rows in set (0.00 sec)
mysql>
- 使用
source命令执行.sql文件的SQL语句
mysql
mysql> source /root/108_class/9_test_db.sql
# 也可以使用缩写形式
mysql> \. /root/108_class/9_test_db.sql
# 中间省略...
Query OK, 0 rows affected (0.00 sec)
如果是非root用户会有权限问题,但是他不会报错。可以用下面的命令来看:
mysql
\! cat /root/108_class/9_test_db.sql
- 查看数据库并查询数据,验证导入是否成功
mysql
mysql> show databases; # 查看数据库
+--------------------+
| Database |
+--------------------+
| db1 |
| helloworld |
| information_schema |
| mysql |
| performance_schema |
| scott |
| sys |
| test_db | # 创建成功
+--------------------+
8 rows in set (0.00 sec)
mysql> use test_db # 选择数据库
Database changed
mysql> show tables; # 查看所有表
+-------------------+
| Tables_in_test_db |
+-------------------+
| classes |
| course |
| score |
| student |
+-------------------+
4 rows in set (0.00 sec)
mysql> select * from student; # 查询数据
+----+-------+--------+------------+
| id | sn | name | mail |
+----+-------+--------+------------+
| 1 | 50001 | 张三 | zs@bit.com |
| 2 | 50002 | 李四 | ls@bit.com |
| 3 | 50003 | 王五 | ww@bit.com |
| 4 | 50004 | 赵六 | zl@bit.com |
| 5 | 50005 | 钱七 | qq@bit.com |
+----+-------+--------+------------+
5 rows in set (0.00 sec)
3.5.2 使用mysql客户端导入
直接使用
mysql客户端程序导入.sql文件并执行相应的SQL语句,可以使用以下命令:
mysql
mysql db_name < text_file # 在指定的数据库下执行SQL,前提是数据库必须提前建立好
mysql < text_file # 不指定数据库.sql中必须有USE [database_name],来指定要操作的数据库
因为我之前已经导入了,我先删一下:
mysql
mysql> drop database test_db;
Query OK, 4 rows affected (0.05 sec)
mysql> quit
Bye
mysql
root@iZuf68hz06p6s2809gl3i1Z:~/108_class# mysql < /root/108_class/9_test_db.sql -uroot -p
Enter password:
root@iZuf68hz06p6s2809gl3i1Z:~/108_class#
这里什么提示都没有,就代表没有保存。
登录数据库并验证是否导入成功。
可以根据实际需要选择导入
.sql的方式。
mysql
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| db1 |
| helloworld |
| information_schema |
| mysql |
| performance_schema |
| scott |
| sys |
| test_db | # 删除的数据库又出现了
+--------------------+
8 rows in set (0.00 sec)
mysql>