Tangwx

Tangwx

博客网站

MySQL数据库

MySQL#

参考链接:

数据库 day1—— 初识数据库 - Eva_J - 博客园 (cnblogs.com) 版本:5.6.44

Django 使用 MySQL 数据库 - 杨仕航的博客 (yshblog.com) 版本:8.0.11

image-20210727081016044

1 下载和安装#

mysql 为我们提供开源的安装在各个操作系统上的安装包,包括 mac,linux,windows。

mysql 的安装、启动和基础配置 —— linux 版本 - Eva_J - 博客园 (cnblogs.com)

mysql 的安装、启动和基础配置 —— mac 版本 - Eva_J - 博客园 (cnblogs.com)

mysql 的安装、启动和基础配置 —— windows 版本 - Eva_J - 博客园 (cnblogs.com)

windows 下载教程#

第一步:打开网址,https://www.mysql.com,点击 downloads 之后跳转到https://www.mysql.com/download

第二步 :跳转至网址https://dev.mysql.com/downloads/,选择 Community 选项

第三步 :点击 MySQL Community Server 进入https://dev.mysql.com/downloads/mysql/页面,再点击 5.6 版本的数据库

第四步:windows 操作系统 点击 5.6 版本之后会跳转到https://dev.mysql.com/downloads/mysql/5.6.html#downloads 网址,页面如下,确认好要下载的版本和操作系统,点击 Download

第五步:可以不用登陆或者注册,直接点击 No thanks,just start my download 就可以下载了。

windows 安装教程#

解压#

下载的 zip 文件解压,将解压之后的文件夹放到任意目录下,这个目录就是 mysql 的安装目录。路径必须全英文不带空格。我安装在D:\software\MySql\mysql-5.6.44-winx64下。

配置#

打开目录,会看到 my-default.ini 配置文件,复制这个配置文件可以重命名为 my.ini 或者 my.cnf

将 my.ini 中的文件拖到 pycharm 中来,因为 pycharm 编码格式是 utf-8

将文件中的内容删除,将下列代码复制粘贴到 my.ini 文件中

[mysql]
# 设置mysql客户端默认字符集
default-character-set=utf8
[mysqld]
#设置3306端口
port = 3306
# 设置mysql的安装目录
basedir=C:\Program Files\mysql-5.6.39-winx64
# 设置mysql数据库的数据的存放目录
datadir=C:\Program Files\mysql-5.6.39-winx64\data
# 允许最大连接数
max_connections=200
# 服务端使用的字符集默认为8比特编码的latin1字符集
character-set-server=utf8
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB

修改这些内容:

# 设置mysql的安装目录
basedir=D:\software\MySql\mysql-5.6.44-winx64
# 设置mysql数据库的数据的存放目录
datadir=D:\software\MySql\mysql-5.6.44-winx64\data

删除 my.ini 每行文档最尾端的多余空格

配置环境变量#

往系统环境变量 ->path 中新建一个变量,将 bin 目录添加到新建的环境变量中D:\software\MySql\mysql-5.6.44-winx64\bin再确定保存即可。

安装 MySQL 服务#

以管理员身份打开 cmd 窗口后,将目录切换到你解压文件的 bin 目录,输入 mysqld install 回车运行

启动 MySQL 服务#

以管理员身份在 cmd 中输入 start mysql

C:\windows\system32>net start mysql
请求的服务已经启动。

请键入 NET HELPMSG 2182 以获得更多的帮助。

服务启动成功之后,就可以登录了,输入mysql -uroot -p(第一次登录没有密码,直接按回车过)

C:\windows\system32>mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.23 MySQL Community Server - GPL

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>

停止 MySQL 服务net stop mysql

C:\windows\system32>net stop mysql
MySQL 服务正在停止.
MySQL 服务已成功停止。

若要重启 MySQL 服务,windows 中需要先 stop 再 start,且 MySQL 是开机自启动项目,开机后会自动 start。

客户端可以是 python 代码也可以是一个程序,mysql.exe 是一个客户端,mysql -u 用户名 -p 密码登陆 mysql。

2 MySQL 中的用户和权限#

在安装数据库之后,有一个最高权限用户 root

MySQL server 端的 ip 用户名 / 密码

mysql -h 192.168.xx.xx -uroot -p 密码

我们的 MySQL 客户端不仅可以连接本地的数据库,还可以连接网络上的某一个数据库的 server 端

查看当前用户#

在 MySQL 环境内运行select user();注意这最后的英文分号;

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

给当前用户添加密码#

在 MySQL 环境内运行set password = password('密码');注意这最后的英文分号;如果不输入分号则会一直显示 -> 无法退出,直到你输入;

新版本的 mysql 修改密码应该用这一条 alter user 'root'@'localhost' identified by '123';

我们这个版本仍然使用set password = password('密码');

创建用户账号#

create user 'name'@'192.168.43.%' identified by '密码';
C:\windows\system32>mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.23 MySQL Community Server - GPL

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> create user 'name'@'192.168.31.%' identified by '123'
    -> ;
Query OK, 0 rows affected (0.09 sec)

mysql> exit
Bye

远程连接#

mysql -uname -p123 -h192.168.31.144
mysql -u用户名 -p密码 -hip -P端口号
mysql -uwanlx -pwanlx -h139.196.217.70 -P8098
C:\windows\system32>mysql -uname -p123 -h192.168.31.144
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 10
Server version: 8.0.23 MySQL Community Server - GPL

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 user();
+----------------------+
| user()               |
+----------------------+
| name@LAPTOP-URS4B7MF |
+----------------------+
1 row in set (0.00 sec)

mysql>

查看文件夹#

show databases;

创建文件夹#

create database 文件夹名
show grant for '用户名'@'192.168.31.%'

提升用户权限#

grant all on name.* to 'name'@'192.168.31.%';
flush privileges;

授权并创建用户#

grant all on name.* to 'alex'@'%' identified by '123';

创建一个名为 alex 的用户,密码为 123,只要和我同一个网段都可以控制 name 文件夹里的所有内容。实际使用报错,未解决。

mysql> grand all on name.* to 'alex'@'%';
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 'grand all on name.* to 'alex'@'%'' at line 1

我所使用的命令:

mysql -uroot -p
mysql -uname -p123 -h192.168.31.144

3 sql 语句#

SQL : 结构化查询语言 (Structured Query Language) 简称 SQL (发音:/ˈes kjuː ˈel/ "S-Q-L"),是一种特殊目的的编程语言,是一种数据库查询和程序设计语言,用于存取数据以及查询、更新和管理关系数据库系统

  SQL 语言主要用于存取数据、查询数据、更新数据和管理关系数据库系统,SQL 语言由 IBM 开发。SQL 语言分为 3 种类型:

  1、DDL 语句 数据库定义语言: 数据库、表、视图、索引、存储过程,例如 CREATE DROP ALTER

  2、DML 语句 数据库操纵语言: 插入数据 INSERT、删除数据 DELETE、更新数据 UPDATE、查询数据 SELECT

  3、DCL 语句 数据库控制语言: 例如控制用户的访问权限 GRANT、REVOKE

库 表 数据#

先创建库,再创建表 DDL 数据库定义语言

存储数据,删除数据,修改数据,查询数据 DML 数据库操纵语句

库操作#

create database 数据库名;

查询当前有多少库:show databases;

查看当前使用的数据库:select database();

切换到这个数据库(文件夹)下:use 数据库名字;

drop database 数据库的名字 删库跑路!👀🤣🏃‍♂️

表操作#

查看当前文件夹中有多少张表show tables;

mysql> show tables;
Empty set (0.06 sec)

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

创建表create table 表的名字(字段命名 数据类型(长度));

create table student(id int,name char(10));

删除表drop tables 表名;#

查看表结构desc 表名

mysql> desc student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | YES  |     | NULL    |       |
| name  | char(10) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)

操作表中数据#

数据的增加insert into 表名 values (字段1,字段2);#
mysql> insert into student values (2,'zhangsan');
Query OK, 1 row affected (0.01 sec)
数据的查看select * from 表名;#
mysql> select * from student;
+------+----------+
| id   | name     |
+------+----------+
|    1 | alex     |
|    2 | zhangsan |
+------+----------+
2 rows in set (0.01 sec)
数据的修改update 表 set 字段名=值;#

若直接update student set name = 'yuan';则会将 name 下所有的数据都修改成 yuan

mysql> update student set name = 'wusir'where id=2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from student;
+------+-------+
| id   | name  |
+------+-------+
|    1 | alex  |
|    2 | wusir |
+------+-------+
2 rows in set (0.00 sec)
数据的删除delete from 表名字;#

若直接执行上述,则会把整个表删除

mysql> delete from student where id=1;
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;
+------+-------+
| id   | name  |
+------+-------+
|    2 | wusir |
+------+-------+
1 row in set (0.00 sec)

4 表操作#

存储引擎#

mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
| CSV                | YES     | CSV storage engine                                             | NO           | NO   | NO         |
| FEDERATED          | NO      | Federated MySQL storage engine                                 | NULL         | NULL | NULL       |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                             | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and foreign keys     | YES          | YES  | YES        |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                         | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)

mysql 中的存储引擎

表结构和表数据是分开存储的。

存储方式1:MyISAM MySQL5.5及以下版本默认存储方式

表结构、表数据、索引

支持表级锁 不支持事务、不支持行级锁、不支持外键

存储方式2: InnoDB MySQL5.6及以上默认存储方式

	`表结构、表数据 `

支持事务、行级锁、外键 ,也支持表级锁

​ 行级锁:

存储方式3:MEMORY 内存

表结构

优势:增删改查都很快

劣势:重启数据消失、容量有限

查看相关配置#

mysql> show variables like '%engine%';
+-----------------------------------------+---------------+
| Variable_name                           | Value         |
+-----------------------------------------+---------------+
| default_storage_engine                  | InnoDB        |
| default_tmp_storage_engine              | InnoDB        |
| disabled_storage_engines                |               |
| internal_tmp_mem_storage_engine         | TempTable     |
| secondary_engine_cost_threshold         | 100000.000000 |
| show_create_table_skip_secondary_engine | OFF           |
| use_secondary_engine                    | ON            |
+-----------------------------------------+---------------+
7 rows in set, 1 warning (0.00 sec)

创建表create table t1 (id int,name char(10));;换成\G可以格式整理

查看表结构show create table 表名; 能看到和这张表相关的所有信息

desc 表名; describe 表名;两张方式查看表结构都是一样的,前者是简写,但这两种方式都只能查看表的字段基础信息。

创建表时同时指定存储引擎create table t2 (id int,name char(10)) engine=myisam;

mysql> create table t2 (id int,name char(10)) engine=myisam;
Query OK, 0 rows affected (0.01 sec)

mysql> show create table t2\G
*************************** 1. row ***************************
       Table: t2
Create Table: CREATE TABLE `t2` (
  `id` int DEFAULT NULL,
  `name` char(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| demo               |
| information_schema |
| mysql              |
| name               |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.02 sec)

mysql> create database demo_1;
Query OK, 1 row affected (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| demo               |
| demo_1             |
| information_schema |
| mysql              |
| name               |
| performance_schema |
| sys                |
+--------------------+
7 rows in set (0.00 sec)

mysql> use demo_1
Database changed
mysql> select database();
+------------+
| database() |
+------------+
| demo_1     |
+------------+
1 row in set (0.00 sec)

mysql> create table t1 (id int,name char(10))
    -> ;
Query OK, 0 rows affected (0.07 sec)

mysql> show create table t1;
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                   |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
| t1    | CREATE TABLE `t1` (
  `id` int DEFAULT NULL,
  `name` char(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | YES  |     | NULL    |       |
| name  | char(10) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> describe t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | YES  |     | NULL    |       |
| name  | char(10) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql>

索引 - 数据库目录#

创建表#

create table 表名(字段1 类型);

MySQL 基础数据类型#

数值类型#

MySQL 支持所有标准 SQL 数值数据类型。

这些类型包括严格数值数据类型 (INTEGER、SMALLINT、DECIMAL 和 NUMERIC),以及近似数值数据类型 (FLOAT、REAL 和 DOUBLE PRECISION)。

关键字 INT 是 INTEGER 的同义词,关键字 DEC 是 DECIMAL 的同义词。

MySQL 支持的整数类型有 TINYINT、MEDIUMINT 和 BIGINT。下面的表显示了需要的每个整数类型的存储和范围。

对于小数的表示,MYSQL 分为两种方式:浮点数和定点数。浮点数包括 float (单精度) 和 double (双精度), 而定点数只有 decimal 一种,在 mysql 中以字符串的形式存放,比浮点数更精确,适合用来表示货币等精度高的数据。

BIT 数据类型保存位字段值,并且支持 MyISAM、MEMORY、InnoDB 和 BDB 表。

类型大小范围(有符号)范围(无符号)unsigned 约束用途
TINYINT1 字节(-128,127)(0,255)小整数值
SMALLINT2 字节(-32 768,32 767)(0,65 535)大整数值
MEDIUMINT3 字节(-8 388 608,8 388 607)(0,16 777 215)大整数值
INT 或 INTEGER4 字节(-2 147 483 648,2 147 483 647)(0,4 294 967 295)大整数值
BIGINT8 字节(-9 233 372 036 854 775 808,9 223 372 036 854 775 807)(0,18 446 744 073 709 551 615)极大整数值
FLOAT4 字节 float (255,30)(-3.402 823 466 E+38,-1.175 494 351 E-38),0,(1.175 494 351 E-38,3.402 823 466 351 E+38)0,(1.175 494 351 E-38,3.402 823 466 E+38)单精度 浮点数值
DOUBLE8 字节 double (255,30)(-1.797 693 134 862 315 7 E+308,-2.225 073 858 507 201 4 E-308),0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308)0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308)双精度 浮点数值
DECIMAL对 DECIMAL (M,D) ,如果 M>D,为 M+2 否则为 D+2double (65,30)依赖于 M 和 D 的值依赖于 M 和 D 的值小数值

int 默认是有符号的,他能表示的范围不被宽度约束。

decimal 存储十分精准,如果不指定则默认(10,0),如果要指定则最多存(25,30)总共存 65 位,其中小数点前存 25 位,小数点后最多存 30 位

日期时间类型#

表示时间值的日期和时间类型为 DATETIME、DATE、TIMESTAMP、TIME 和 YEAR。

每个时间类型有一个有效值范围和一个 "零" 值,当指定不合法的 MySQL 不能表示的值时使用 "零" 值。

TIMESTAMP 类型有专有的自动更新特性,将在后面描述。

类型大小 (字节)范围格式用途
DATE31000-01-01/9999-12-31YYYY-MM-DD年月日
TIME3'-838:59:59'/'838:59:59'HH:MM时分秒
YEAR11901/2155YYYY年份值
DATETIME81000-01-01 00:00:00/9999-12-31 23:59:59YYYY-MM-DD HH:MM年月日时分秒
TIMESTAMP41970-01-01 00:00:00/2038 结束时间是第 2147483647 秒,北京时间 2038-1-19 11:14:07,格林尼治时间 2038 年 1 月 19 日 凌晨 03:14:07YYYYMMDD HHMMSS混合日期和时间值,时间戳
mysql> create table t4 (d date,t time,dt datetime);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t4;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| d     | date     | YES  |     | NULL    |       |
| t     | time     | YES  |     | NULL    |       |
| dt    | datetime | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql> insert into t4 values (now(),now(),now());
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> select * from t4;
+------------+----------+---------------------+
| d          | t        | dt                  |
+------------+----------+---------------------+
| 2018-09-21 | 14:51:51 | 2018-09-21 14:51:51 |
+------------+----------+---------------------+
1 row in set (0.00 sec)

mysql> insert into t4 values (null,null,null);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t4;
+------------+----------+---------------------+
| d          | t        | dt                  |
+------------+----------+---------------------+
| 2018-09-21 | 14:51:51 | 2018-09-21 14:51:51 |
| NULL       | NULL     | NULL                |
+------------+----------+---------------------+
2 rows in set (0.00 sec)

date/time/datetime示例
mysql> create table t5 (id1 timestamp);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t5;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type      | Null | Key | Default           | Extra                       |
+-------+-----------+------+-----+-------------------+-----------------------------+
| id1   | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
1 row in set (0.00 sec)

# 插入数据null,会自动插入当前时间的时间
mysql> insert into t5 values (null);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t5;
+---------------------+
| id1                 |
+---------------------+
| 2018-09-21 14:56:50 |
+---------------------+
1 row in set (0.00 sec)

#添加一列 默认值是'0000-00-00 00:00:00'
mysql> alter table t5 add id2 timestamp;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table t5 \G;
*************************** 1. row ***************************
       Table: t5
Create Table: CREATE TABLE `t5` (
  `id1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `id2` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

# 手动修改新的列默认值为当前时间
mysql> alter table t5 modify id2 timestamp default current_timestamp;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table t5 \G;
*************************** 1. row ***************************
       Table: t5
Create Table: CREATE TABLE `t5` (
  `id1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `id2` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR: 
No query specified

mysql> insert into t5 values (null,null);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t5;
+---------------------+---------------------+
| id1                 | id2                 |
+---------------------+---------------------+
| 2018-09-21 14:56:50 | 0000-00-00 00:00:00 |
| 2018-09-21 14:59:31 | 2018-09-21 14:59:31 |
+---------------------+---------------------+
2 rows in set (0.00 sec)

timestamp示例
mysql> create table t6 (t1 timestamp);
Query OK, 0 rows affected (0.02 sec)

mysql> desc t6;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type      | Null | Key | Default           | Extra                       |
+-------+-----------+------+-----+-------------------+-----------------------------+
| t1    | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
1 row in set (0.01 sec)

mysql> insert into t6 values (19700101080001);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t6;
+---------------------+
| t1                  |
+---------------------+
| 1970-01-01 08:00:01 |
+---------------------+
1 row in set (0.00 sec)
# timestamp时间的下限是19700101080001
mysql> insert into t6 values (19700101080000);
ERROR 1292 (22007): Incorrect datetime value: '19700101080000' for column 't1' at row 1

mysql> insert into t6 values ('2038-01-19 11:14:07');
Query OK, 1 row affected (0.00 sec)
# timestamp时间的上限是2038-01-19 11:14:07
mysql> insert into t6 values ('2038-01-19 11:14:08');
ERROR 1292 (22007): Incorrect datetime value: '2038-01-19 11:14:08' for column 't1' at row 1
mysql> 

timestamp示例2
mysql> create table t7 (y year);
Query OK, 0 rows affected (0.02 sec)

mysql> insert into t7 values (2018);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t7;
+------+
| y    |
+------+
| 2018 |
+------+
1 row in set (0.00 sec)

year示例
mysql> create table t8 (dt datetime);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t8 values ('2018-9-26 12:20:10');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t8 values ('2018/9/26 12+20+10');
Query OK, 1 row affected (0.00 sec)

mysql> insert into t8 values ('20180926122010');
Query OK, 1 row affected (0.00 sec)

mysql> insert into t8 values (20180926122010);
Query OK, 1 row affected (0.00 sec)

mysql> select * from t8;
+---------------------+
| dt                  |
+---------------------+
| 2018-09-26 12:20:10 |
| 2018-09-26 12:20:10 |
| 2018-09-26 12:20:10 |
| 2018-09-26 12:20:10 |
+---------------------+
4 rows in set (0.00 sec)

datetime示例
字符串类型#

字符串类型指 CHAR、VARCHAR、BINARY、VARBINARY、BLOB、TEXT、ENUM 和 SET。该节描述了这些类型如何工作以及如何在查询中使用这些类型。

类型大小用途
CHAR0-255 字节定长字符串
VARCHAR0-65535 字节变长字符串
TINYBLOB0-255 字节不超过 255 个字符的二进制字符串
TINYTEXT0-255 字节短文本字符串
BLOB0-65 535 字节二进制形式的长文本数据
TEXT0-65 535 字节长文本数据
MEDIUMBLOB0-16 777 215 字节二进制形式的中等长度文本数据
MEDIUMTEXT0-16 777 215 字节中等长度文本数据
LONGBLOB0-4 294 967 295 字节二进制形式的极大文本数据
LONGTEXT0-4 294 967 295 字节极大文本数据

CHAR 和 VARCHAR 类型类似,但它们保存和检索的方式不同。它们的最大长度和是否尾部空格被保留等方面也不同。在存储或检索过程中不进行大小写转换。

CHAR 列的长度固定为创建表是声明的长度,范围 (0-255); 而 VARCHAR 的值是可变长字符串范围 (0-65535)。

mysql> create table t9 (v varchar(4),c char(4));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t9 values ('ab  ','ab  ');
Query OK, 1 row affected (0.00 sec)

# 在检索的时候char数据类型会去掉空格
mysql> select * from t9;
+------+------+
| v    | c    |
+------+------+
| ab   | ab   |
+------+------+
1 row in set (0.00 sec)

# 来看看对查询结果计算的长度
mysql> select length(v),length(c) from t9;
+-----------+-----------+
| length(v) | length(c) |
+-----------+-----------+
|         4 |         2 |
+-----------+-----------+
1 row in set (0.00 sec)

# 给结果拼上一个加号会更清楚
mysql> select concat(v,'+'),concat(c,'+') from t9;
+---------------+---------------+
| concat(v,'+') | concat(c,'+') |
+---------------+---------------+
| ab  +         | ab+           |
+---------------+---------------+
1 row in set (0.00 sec)

# 当存储的长度超出定义的长度,会截断
mysql> insert into t9 values ('abcd  ','abcd  ');
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> select * from t9;
+------+------+
| v    | c    |
+------+------+
| ab   | ab   |
| abcd | abcd |
+------+------+
2 rows in set (0.00 sec)

char/varchar示例

BINARY 和 VARBINARY 类似于 CHAR 和 VARCHAR,不同的是它们包含二进制字符串而不要非二进制字符串。也就是说,它们包含字节字符串而不是字符字符串。这说明它们没有字符集,并且排序和比较基于列值字节的数值值。

BLOB 是一个二进制大对象,可以容纳可变数量的数据。有 4 种 BLOB 类型:TINYBLOB、BLOB、MEDIUMBLOB 和 LONGBLOB。它们区别在于可容纳存储范围不同。

有 4 种 TEXT 类型:TINYTEXT、TEXT、MEDIUMTEXT 和 LONGTEXT。对应的这 4 种 BLOB 类型,可存储的最大长度不同,可根据实际情况选择。

ENUM 和 SET 类型#

ENUM 中文名称叫枚举类型,它的值范围需要在创建表时通过枚举方式显示。ENUM只允许从值集合中选取单个值,而不能一次取多个值

SET 和 ENUM 非常相似,也是一个字符串对象,里面可以包含 0-64 个成员。根据成员的不同,存储上也有所不同。set 类型可以允许值集合中任意选择 1 或多个元素进行组合。对超出范围的内容将不允许注入,而对重复的值将进行自动去重。

类型大小用途
ENUM对 1-255 个成员的枚举需要 1 个字节存储;对于 255-65535 个成员,需要 2 个字节存储;最多允许 65535 个成员。单选:选择性别
SET1-8 个成员的集合,占 1 个字节 9-16 个成员的集合,占 2 个字节 17-24 个成员的集合,占 3 个字节 25-32 个成员的集合,占 4 个字节 33-64 个成员的集合,占 8 个字节多选:兴趣爱好

set/enum 示例

mysql> create table t10 (name char(20),gender enum('female','male'));
Query OK, 0 rows affected (0.01 sec)

# 选择enum('female','male')中的一项作为gender的值,可以正常插入
mysql> insert into t10 values ('nezha','male');
Query OK, 1 row affected (0.00 sec)

# 不能同时插入'male,female'两个值,也不能插入不属于'male,female'的值
mysql> insert into t10 values ('nezha','male,female');
ERROR 1265 (01000): Data truncated for column 'gender' at row 1

mysql> create table t11 (name char(20),hobby set('抽烟','喝酒','烫头','翻车'));
Query OK, 0 rows affected (0.01 sec)

# 可以任意选择set('抽烟','喝酒','烫头','翻车')中的项,并自带去重功能
mysql> insert into t11 values ('yuan','烫头,喝酒,烫头');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t11;
+------+---------------+
| name | hobby        |
+------+---------------+
| yuan | 喝酒,烫头     |
+------+---------------+
1 row in set (0.00 sec)

# 不能选择不属于set('抽烟','喝酒','烫头','翻车')中的项,
mysql> insert into t11 values ('alex','烫头,翻车,看妹子');
ERROR 1265 (01000): Data truncated for column 'hobby' at row 1

表的约束#

设置某一个数字为无符号unsigned

约束某一个字段不能为空not null

给某个字段设置默认值default

设置某一个字段不能重复unique

设置某个 int 类型的字段自动增加auto_increment

设置某一个字段非空且不能重复primary key

外键foreign key

联合唯一#
create table t4(
    id int,
    ip char(15),
    server char(10),
    port int,
    unique(ip,port)
);
mysql> create table t4(
    ->     id int,
    ->     ip char(15),
    ->     server char(10),
    ->     port int,
    ->     unique(ip,port)
    -> );
Query OK, 0 rows affected (0.12 sec)

mysql> desc t4;
+--------+----------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| id     | int      | YES  |     | NULL    |       |
| ip     | char(15) | YES  | MUL | NULL    |       |
| server | char(10) | YES  |     | NULL    |       |
| port   | int      | YES  |     | NULL    |       |
+--------+----------+------+-----+---------+-------+
4 rows in set (0.01 sec)

mysql> show create table t4;
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                               |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t4    | CREATE TABLE `t4` (
  `id` int DEFAULT NULL,
  `ip` char(15) DEFAULT NULL,
  `server` char(10) DEFAULT NULL,
  `port` int DEFAULT NULL,
  UNIQUE KEY `ip` (`ip`,`port`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

mysql> insert into t4 values(1,'192.168.12.87','mysql',3306);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t4 values(2,'192.168.12.87','kugou',8000);
Query OK, 1 row affected (0.01 sec)

mysql> insert into t4 values(3,'192.168.12.36','mysql',3306);
Query OK, 1 row affected (0.00 sec)

mysql> insert into t4 values(4,'192.168.12.36','mysql',3306);
ERROR 1062 (23000): Duplicate entry '192.168.12.36-3306' for key 't4.ip'
mysql>
自增auto_increment#

自增字段 必须是数字 且 必须是唯一的 自带非空效果

create table t5(
    id int unique auto_increment,
    username char(10),
    password char(18)
);
mysql> create table t5(
    ->     id int unique auto_increment,
    ->     username char(10),
    ->     password char(18)
    -> );
Query OK, 0 rows affected (0.07 sec)

mysql> desc t5;
+----------+----------+------+-----+---------+----------------+
| Field    | Type     | Null | Key | Default | Extra          |
+----------+----------+------+-----+---------+----------------+
| id       | int      | NO   | PRI | NULL    | auto_increment |
| username | char(10) | YES  |     | NULL    |                |
| password | char(18) | YES  |     | NULL    |                |
+----------+----------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> insert into t5(username,password) value('alex','alex3345');
Query OK, 1 row affected (0.01 sec)

mysql> insert into t5(username,password) value('alex','alex3345');
Query OK, 1 row affected (0.00 sec)

mysql> insert into t5(username,password) value('alex','alex3345');
Query OK, 1 row affected (0.00 sec)

mysql> select * from t5;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | alex     | alex3345 |
|  2 | alex     | alex3345 |
|  3 | alex     | alex3345 |
+----+----------+----------+
3 rows in set (0.00 sec)

mysql>show create table t5;
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                 |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| t5    | CREATE TABLE `t5` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` char(10) DEFAULT NULL,
  `password` char(18) DEFAULT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>
主键primary key#

一张表只能有一个主键

一张表可以没有主键,但每张表最好设置一个主键

约束这个字段 非空(not null)且唯一(unique)

create table t6(
id int not null unique,
name char(12) not null unique
);
mysql> create table t6(
    -> id int not null unique,
    -> name char(12) not null unique
    -> );
Query OK, 0 rows affected (0.03 sec)
mysql> desc t6;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | NO   | PRI | NULL    |       |
| name  | char(12) | NO   | UNI | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)

你指定的第一个非空且唯一的字段会被定义成主键

create table t7(
    id int primary key,
    name char(12) not null unique
);
mysql> create table t7(
    ->     id int primary key,
    ->     name char(12) not null unique
    -> );
Query OK, 0 rows affected (0.08 sec)

mysql> desc t7;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | NO   | PRI | NULL    |       |
| name  | char(12) | NO   | UNI | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.02 sec)

直接指定 primary key 默认 非空且唯一

联合主键#
create table t8(
    id int,
    ip char(15),
    server char(10),
    port int,
    primary key(ip,port)
);
外键foreign key涉及到两张表#

员工表

id age gender salary hire_date postid

部门表

postname postid post_comment post_phone

mysql> create table post(
    -> postid int primary key,
    -> postname char(10) not null unique,
    -> comment varchar(255),
    -> phone_num char(11)
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql> create table staff(
    -> id int primary key auto_increment,
    -> age int,
    -> gender enum('male','female'),
    -> salary float(8,2),
    -> hire_date date,
    -> post_id int,
    -> foreign key(post_id) references post(postid)
    -> );
Query OK, 0 rows affected, 1 warning (0.04 sec)

mysql> desc staff;
+-----------+-----------------------+------+-----+---------+----------------+
| Field     | Type                  | Null | Key | Default | Extra          |
+-----------+-----------------------+------+-----+---------+----------------+
| id        | int                   | NO   | PRI | NULL    | auto_increment |
| age       | int                   | YES  |     | NULL    |                |
| gender    | enum('male','female') | YES  |     | NULL    |                |
| salary    | float(8,2)            | YES  |     | NULL    |                |
| hire_date | date                  | YES  |     | NULL    |                |
| post_id   | int                   | YES  | MUL | NULL    |                |
+-----------+-----------------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)

mysql> desc post;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| postid    | int          | NO   | PRI | NULL    |       |
| postname  | char(10)     | NO   | UNI | NULL    |       |
| comment   | varchar(255) | YES  |     | NULL    |       |
| phone_num | char(11)     | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> show create table staff;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                  |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| staff | CREATE TABLE `staff` (
  `id` int NOT NULL AUTO_INCREMENT,
  `age` int DEFAULT NULL,
  `gender` enum('male','female') DEFAULT NULL,
  `salary` float(8,2) DEFAULT NULL,
  `hire_date` date DEFAULT NULL,
  `post_id` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `post_id` (`post_id`),
  CONSTRAINT `staff_ibfk_1` FOREIGN KEY (`post_id`) REFERENCES `post` (`postid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> insert into post values(1 ,'python部门','不错的团队','01066666666');
Query OK, 1 row affected (0.01 sec)

mysql> insert into staff values(1 ,80,'male',100000,20101010101010,1);
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql>

外键至少关联一个主键,注意:先创建被关联的表再创建外键表,例如上方先创建部门表再创建员工表。

级联删除和级联更新on update cascade on delete cascade#
mysql> create table staff2(
    -> id int primary key auto_increment,
    -> age int,
    -> gender enum('male','female'),
    -> salary float(8,2),
    -> hire_date date,
    -> post_id int,
    -> foreign key(post_id) references post(postid) on update cascade on delete cascade
    -> );

on delete (了解)

. cascade方式
在父表上update/delete记录时,同步update/delete掉子表的匹配记录 

   . set null方式
在父表上update/delete记录时,将子表上匹配记录的列设为null
要注意子表的外键列不能为not null  

   . No action方式
如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作  

   . Restrict方式
同no action, 都是立即检查外键约束

   . Set default方式
父表有变更时,子表将外键列设置成一个默认的值 但Innodb不能识别

修改表#

语法:

  1. 修改表名
    ALTER TABLE 表名
    RENAME 新表名;

  2. 增加字段
    ALTER TABLE 表名
    ADD 字段名 数据类型 [完整性约束条件…],
    ADD 字段名 数据类型 [完整性约束条件…];

  3. 删除字段
    ALTER TABLE 表名
    DROP 字段名;

  4. 修改字段
    ALTER TABLE 表名
    MODIFY 字段名 数据类型 [完整性约束条件…];
    ALTER TABLE 表名
    CHANGE 旧字段名 新字段名 旧数据类型 [完整性约束条件…];
    ALTER TABLE 表名
    CHANGE 旧字段名 新字段名 新数据类型 [完整性约束条件…];

5. 修改字段排列顺序 / 在增加的时候指定字段位置
ALTER TABLE 表名
ADD 字段名 数据类型 [完整性约束条件…] FIRST;
ALTER TABLE 表名
ADD 字段名 数据类型 [完整性约束条件…] AFTER 字段名;
ALTER TABLE 表名
CHANGE 字段名 旧字段名 新字段名 新数据类型 [完整性约束条件…] FIRST;
ALTER TABLE 表名
MODIFY 字段名 数据类型 [完整性约束条件…] AFTER 字段名;

表关系#

两张表之间的关系

多对一

=====================多对一=====================
create table press(
id int primary key auto_increment,
name varchar(20)
);

create table book(
id int primary key auto_increment,
name varchar(20),
press_id int not null,
foreign key(press_id) references press(id)
on delete cascade
on update cascade
);


insert into press(name) values
('北京工业地雷出版社'),
('人民音乐不好听出版社'),
('知识产权没有用出版社')
;

insert into book(name,press_id) values
('九阳神功',1),
('九阴真经',2),
('九阴白骨爪',2),
('独孤九剑',3),
('降龙十巴掌',2),
('葵花宝典',3)
;

sql示例

一对一

create table customer(
    -> id int primary key auto_increment,
    -> name varchar(20) not null,
    -> qq varchar(10) not null,
    -> phone char(16) not null
    -> );

create table student(
    -> id int primary key auto_increment,
    -> class_name varchar(20) not null,
    -> customer_id int unique, #该字段一定要是唯一的
    -> foreign key(customer_id) references customer(id) #外键的字段一定要保证unique
    -> on delete cascade
    -> on update cascade
    -> );

#增加客户
mysql> insert into customer(name,qq,phone) values
    -> ('韩蕾','31811231',13811341220),
    -> ('杨澜','123123123',15213146809),
    -> ('翁惠天','283818181',1867141331),
    -> ('杨宗河','283818181',1851143312),
    -> ('袁承明','888818181',1861243314),
    -> ('袁清','112312312',18811431230)

mysql> #增加学生
mysql> insert into student(class_name,customer_id) values
    -> ('脱产1班',3),
    -> ('周末1期',4),
    -> ('周末1期',5)
    -> ;
sql示例

多对多

=====================多对多=====================
create table author(
id int primary key auto_increment,
name varchar(20)
);


#这张表就存放作者表与书表的关系,即查询二者的关系查这表就可以了
create table author2book(
id int not null unique auto_increment,
author_id int not null,
book_id int not null,
constraint fk_author foreign key(author_id) references author(id)
on delete cascade
on update cascade,
constraint fk_book foreign key(book_id) references book(id)
on delete cascade
on update cascade,
primary key(author_id,book_id)
);


#插入四个作者,id依次排开
insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq');

#每个作者与自己的代表作如下
egon: 
九阳神功
九阴真经
九阴白骨爪
独孤九剑
降龙十巴掌
葵花宝典
alex: 
九阳神功
葵花宝典
yuanhao:
独孤九剑
降龙十巴掌
葵花宝典
wpq:
九阳神功


insert into author2book(author_id,book_id) values
(1,1),
(1,2),
(1,3),
(1,4),
(1,5),
(1,6),
(2,1),
(2,6),
(3,4),
(3,5),
(3,6),
(4,1)
;
sql示例

数据操作#

增加insert#

insert into 表名 values (值...);所有的在这个表中的字段都需要按顺序填写在这里

insert into 表名 (字段名,字段名...) values (值...);所有在字段位置填写了名字的字段必须和后面的值一一对应

insert into 表名 value (值...);一次性只能写入一行数据,values 可以一次写入多行

删除delete#

delete from 表 where 条件;

修改update#

update 表 set 字段=新的值 where 条件;

查询select#

select * from 表名; select 字段 from 表名;

去除重复项select distinct 字段 from 表名;

四则运算select 字段*10 from 表名;同时可以重命名四则运算后的名字select 字段*10 as 新名字 from 表名;或者去掉 as 保留空格

where 语句#

比较运算#

> < = >= <= != <> (也表示不等于)

范围运算#

​ 多选一 in

select * from 表名 where 字段名 in (值1,值2,值3);

​ 在一个模糊的范围内

​ 在一个数值区间 [a,b] between

select * from 表名 where 字段名 between a and b;

​ 字符串的模糊查询like

​ 通配符 %匹配任意长度的任意内容

select * from 表名 where 字段名 like '模糊字符%';

​ 通配符 _匹配一个字符长度的任意内容,缺多少位就要加多少个_

select * from 表名 where 字段名 like '模糊字符__';

​ 正则匹配regexp

select * from 表名 where 字段名 regexp '正则表达式';

逻辑运算 - 条件的拼接#

andornot

分组 group by#

select * from 表名 group by 字段;

会把在 group by 后面的这个字段中的每一个不同的项都保留下来,并把这一项的所有值归为一组

聚合#

count(字段)统计这个字段有多少项select count(*) from 表名;

sum(字段)统计这个字段对应数值的和

avg(字段)统计这个字段对应数值的平均值

min(字段)统计这个字段对应数值的最小值

max(字段)统计这个字段对应数值的最大值

分组聚合#

select count(*) from 表名 group by 字段;

select sum(字段) from 表名 group by 字段;

过滤having#

having 总是和 group by 一起用

select 字段 from 表名 group by 字段名 having 条件;

select post from employee group by post having count(*) > 3;

查询排序order by#

select * from 表名 order by 字段名;默认从小到大排,默认是 asc 可省略不写

select * from 表名 order by 字段名 desc;从大到小排

多列排序:select * from 表名 order by 字段名1 asc,字段名2 desc;可以指定第一个字段升序排列,再第一个字段相同的情况下按第二个字段降序排列

限制查询的记录数limit#

select * from 表名 order by 字段名 desc limit 取前多少名的值;

分页操作

select * from 表名 order by 字段名 desc limit 0,5;从 0 开始取,取前 5 个值

select * from 表名 order by 字段名 desc limit 5,5;从 5 开始取,取后面 5 个

limit m,n 等价于 limit n offset m

他们的顺序不能变select distinct 需要显示的列 from 表 where 条件 group by 分组 having 过滤组条件 order by 排序 limit 前n条

正则查询#

敲错换行了可用\c退出

操作 Linux 服务器下的数据:

连接 mysql 数据库

C:\Users\HP>mysql -uwanlx -pwanlx -h139.196.217.70 -P8098
mysql: [Warning] Using a passwrord on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 29
Server version: 5.5.5-10.6.4-MariaDB MariaDB Server

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 |
| iot                |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
6 rows in set (0.03 sec)

mysql> select database();
+------------+
| database() |
+------------+
| NULL       |
+------------+
1 row in set (0.05 sec)

进入库

mysql> use iot;
Database changed
mysql> select database();
+------------+
| database() |
+------------+
| iot        |
+------------+
1 row in set (0.05 sec)

查看表

mysql> show tables;
+---------------+
| Tables_in_iot |
+---------------+
| ClassInfo     |
| StuInfo       |
+---------------+
2 rows in set (0.06 sec)

查看表结构

mysql> desc StuInfo;
+---------+------------------+------+-----+---------+----------------+
| Field   | Type             | Null | Key | Default | Extra          |
+---------+------------------+------+-----+---------+----------------+
| id      | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name    | varchar(80)      | NO   |     | NULL    |                |
| class   | varchar(80)      | NO   |     | NULL    |                |
| age     | smallint(6)      | YES  |     | NULL    |                |
| address | varchar(256)     | YES  |     | NULL    |                |
+---------+------------------+------+-----+---------+----------------+
5 rows in set (0.03 sec)

查看表内容

mysql> select * from StuInfo;
+----+--------+-----------------------+------+--------------------+
| id | name   | class                 | age  | address            |
+----+--------+-----------------------+------+--------------------+
|  1 | 万里霞 | 09级自动化2班         |   31 | 江西省新余市分宜县 |
|  2 | 汤清华 | 17级自动化1班         |   20 | 江西省赣州市       |
|  3 | 张三   | 19级自动化1班         |   21 | 江西省赣州市       |
|  4 | 李四   | 17级自动化1班         |   22 | 江西省赣州市       |
|  5 | 黄石海 | 19级物联网工程本科1班 |   22 | 江西省九江市       |
|  6 | 贾景旗 | 19级物联网工程本科2班 |   22 | 山西省运城市       |
|  7 | 严淦   | 19级物联网工程本科2班 |   22 | 江西省赣州市       |
|  8 | 汤汶熙 | 19级自动化1班         |   22 | 江西省赣州市       |
+----+--------+-----------------------+------+--------------------+
8 rows in set (0.08 sec)

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。