Tangwx

Tangwx

博客网站

MySQL Database

MySQL#

Reference links:

Database Day 1 - Introduction to Databases - Eva_J - Blog Garden (cnblogs.com) Version: 5.6.44

Django Using MySQL Database - Yang Shihang's Blog (yshblog.com) Version: 8.0.11

image-20210727081016044

1 Download and Installation#

MySQL provides us with open-source installation packages for various operating systems, including mac, linux, and windows.

MySQL Installation, Startup, and Basic Configuration - Linux Version - Eva_J - Blog Garden (cnblogs.com)

MySQL Installation, Startup, and Basic Configuration - Mac Version - Eva_J - Blog Garden (cnblogs.com)

MySQL Installation, Startup, and Basic Configuration - Windows Version - Eva_J - Blog Garden (cnblogs.com)

Windows Download Tutorial#

Step 1: Open the website, https://www.mysql.com, click on downloads, and then redirect to https://www.mysql.com/download.

Step 2: Redirect to the website https://dev.mysql.com/downloads/, and select the Community option.

Step 3: Click on MySQL Community Server to enter the https://dev.mysql.com/downloads/mysql/ page, then click on the 5.6 version of the database.

Step 4: For Windows operating systems, clicking on the 5.6 version will redirect to https://dev.mysql.com/downloads/mysql/5.6.html#downloads. Confirm the version and operating system you want to download, then click Download.

Step 5: You can download directly by clicking No thanks, just start my download without logging in or registering.

Windows Installation Tutorial#

Unzip#

Unzip the downloaded zip file and place the unzipped folder in any directory; this directory will be the MySQL installation directory. The path must be entirely in English without spaces. I installed it in D:\software\MySql\mysql-5.6.44-winx64.

Configuration#

Open the directory, and you will see the my-default.ini configuration file. Copy this configuration file and rename it to my.ini or my.cnf.

Drag the my.ini file into PyCharm, as PyCharm's encoding format is UTF-8.

Delete the content in the file and copy the following code into the my.ini file:

[mysql]
# Set the default character set for the MySQL client
default-character-set=utf8
[mysqld]
# Set the port to 3306
port = 3306
# Set the MySQL installation directory
basedir=C:\Program Files\mysql-5.6.39-winx64
# Set the directory for storing MySQL database data
datadir=C:\Program Files\mysql-5.6.39-winx64\data
# Allow maximum connections
max_connections=200
# The default character set used by the server is the 8-bit encoded latin1 character set
character-set-server=utf8
# The default storage engine used when creating new tables
default-storage-engine=INNODB

Modify these contents:

# Set the MySQL installation directory
basedir=D:\software\MySql\mysql-5.6.44-winx64
# Set the directory for storing MySQL database data
datadir=D:\software\MySql\mysql-5.6.44-winx64\data

Remove any extra spaces at the end of each line in my.ini.

Configure Environment Variables#

Create a new variable in the system environment variable -> path, and add the bin directory to the new environment variable D:\software\MySql\mysql-5.6.44-winx64\bin, then confirm and save.

Install MySQL Service#

Open the cmd window as an administrator, switch the directory to the bin directory of your unzipped files, and enter mysqld install, then press Enter to run.

Start MySQL Service#

In cmd, run as administrator: net start mysql

C:\windows\system32>net start mysql
The requested service has already been started.

Please type NET HELPMSG 2182 for more help.

Once the service starts successfully, you can log in by entering mysql -uroot -p (the first login has no password, just press Enter).

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>

Stop the MySQL service with net stop mysql.

C:\windows\system32>net stop mysql
MySQL service is stopping.
MySQL service has been stopped successfully.

To restart the MySQL service, you need to stop and then start it in Windows, and MySQL is set to start automatically when the computer boots.

The client can be Python code or a program; mysql.exe is a client, and you can log in to MySQL with mysql -u username -p password.

2 Users and Permissions in MySQL#

After installing the database, there is a highest privilege user root.

MySQL server IP username/password

mysql -h 192.168.xx.xx -uroot -p password

Our MySQL client can connect not only to local databases but also to a database server on the network.

View Current User#

Run select user(); in the MySQL environment, noting the English semicolon at the end;

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

Add Password for Current User#

Run set password = password('password'); in the MySQL environment, noting the English semicolon at the end; if you do not enter a semicolon, it will keep showing -> unable to exit until you enter it;

In the new version of MySQL, the password should be changed using this command: alter user 'root'@'localhost' identified by '123';

In our version, we still use set password = password('password');

Create User Account#

create user 'name'@'192.168.43.%' identified by 'password';
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

Remote Connection#

mysql -uname -p123 -h192.168.31.144
mysql -u username -p password -h ip -P port
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>

View Databases#

show databases;

Create Database#

create database folder_name
show grant for 'username'@'192.168.31.%'

Grant User Permissions#

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

Authorize and Create User#

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

Create a user named alex with the password 123, who can control all content in the name folder as long as they are in the same subnet. An error occurred during actual use, which was unresolved.

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

The commands I used:

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

3 SQL Statements#

SQL: Structured Query Language, abbreviated as SQL (pronounced: /ˈes kjuː ˈel/ "S-Q-L"), is a special-purpose programming language used for accessing data and querying, updating, and managing relational database systems.

SQL is mainly used for accessing, querying, updating data, and managing relational database systems. SQL was developed by IBM. SQL is divided into three types:

  1. DDL Statements (Data Definition Language): Database, tables, views, indexes, stored procedures, e.g., CREATE DROP ALTER.

  2. DML Statements (Data Manipulation Language): Insert data INSERT, delete data DELETE, update data UPDATE, query data SELECT.

  3. DCL Statements (Data Control Language): For example, controlling user access permissions GRANT, REVOKE.

Database Table Data#

First create a database, then create a table. DDL is the database definition language.

Store data, delete data, modify data, query data. DML is the data manipulation language.

Database Operations#

create database database_name;

Query how many databases currently exist: show databases;

View the currently used database: select database();

Switch to this database (folder): use database_name;

Drop the database: drop database database_name; Run away!👀🤣🏃‍♂️

Table Operations#

Check how many tables are in the current folder: 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 a table: create table table_name(field_name data_type(length));

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

Delete Table: drop tables table_name;#

View table structure: desc table_name;

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)

Operate Data in the Table#

Add Data: insert into table_name values (field1, field2);#
mysql> insert into student values (2,'zhangsan');
Query OK, 1 row affected (0.01 sec)
View Data: select * from table_name;#
mysql> select * from student;
+------+----------+ 
| id   | name     | 
+------+----------+ 
|    1 | alex     | 
|    2 | zhangsan | 
+------+----------+ 
2 rows in set (0.01 sec)
Modify Data: update table set field_name=value;#

If you directly update student set name = 'yuan';, it will change all data in the name column to 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 Data: delete from table_name;#

If you execute the above directly, it will delete the entire table.

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 Table Operations#

Storage Engines#

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)

Storage Engines in MySQL

Table structure and table data are stored separately.

Storage Method 1: MyISAM is the default storage method for MySQL versions 5.5 and below

Table structure, table data, index

Supports table-level locking Does not support transactions, row-level locking, or foreign keys

Storage Method 2: InnoDB is the default storage method for MySQL versions 5.6 and above

	`Table structure, table data `

Supports transactions, row-level locking, foreign keys, and also supports table-level locking

​ Row-level locking:

Storage Method 3: MEMORY

Table structure

Advantages: Fast for insert, delete, update, and query

Disadvantages: Data disappears on restart, limited capacity

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 a table: create table t1 (id int,name char(10)); Replacing ; with \G can format the output.

View table structure: show create table table_name; You can see all information related to this table.

desc table_name; describe table_name; Both ways to view table structure are the same; the former is shorthand, but both can only view basic information about the table's fields.

When creating a table, specify the storage engine: 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>

Index - Database Directory#

Create Table#

create table table_name(field1 type);

Basic Data Types in MySQL#

Numeric Types#

MySQL supports all standard SQL numeric data types.

These types include strict numeric data types (INTEGER, SMALLINT, DECIMAL, and NUMERIC) and approximate numeric data types (FLOAT, REAL, and DOUBLE PRECISION).

The keyword INT is a synonym for INTEGER, and the keyword DEC is a synonym for DECIMAL.

The integer types supported by MySQL are TINYINT, MEDIUMINT, and BIGINT. The following table shows the storage and range required for each integer type.

For decimal representation, MySQL divides it into two types: floating-point and fixed-point. Floating-point types include float (single precision) and double (double precision), while fixed-point types only include decimal, which is stored as a string in MySQL and is more precise than floating-point, suitable for representing high-precision data such as currency.

The BIT data type stores bit field values and supports MyISAM, MEMORY, InnoDB, and BDB tables.

TypeSizeRange (Signed)Range (Unsigned)Purpose
TINYINT1 byte(-128, 127)(0, 255)Small integer value
SMALLINT2 bytes(-32,768, 32,767)(0, 65,535)Large integer value
MEDIUMINT3 bytes(-8,388,608, 8,388,607)(0, 16,777,215)Large integer value
INT or INTEGER4 bytes(-2,147,483,648, 2,147,483,647)(0, 4,294,967,295)Large integer value
BIGINT8 bytes(-9,233,372,036,854,775,808, 9,223,372,036,854,775,807)(0, 18,446,744,073,709,551,615)Extremely large integer value
FLOAT4 bytes float(255,30)(-3.402823466E+38, -1.175494351E-38), 0, (1.175494351E-38, 3.402823466351E+38)0, (1.175494351E-38, 3.402823466E+38)Single precision floating-point value
DOUBLE8 bytes double(255,30)(-1.7976931348623157E+308, -2.2250738585072014E-308), 0, (2.2250738585072014E-308, 1.7976931348623157E+308)0, (2.2250738585072014E-308, 1.7976931348623157E+308)Double precision floating-point value
DECIMALFor DECIMAL(M,D), if M>D, it is M+2; otherwise, it is D+2 double(65,30)Depends on M and DDepends on M and DDecimal value

INT is unsigned by default, and its range is not constrained by width.

DECIMAL is stored very precisely; if not specified, it defaults to (10,0). If specified, it can store a maximum of (25,30), totaling 65 digits, with up to 25 digits before the decimal point and a maximum of 30 digits after the decimal point.

Date and Time Types#

The date and time types that represent time values are DATETIME, DATE, TIMESTAMP, TIME, and YEAR.

Each time type has a valid value range and a "zero" value, which is used when an illegal value that MySQL cannot represent is specified.

The TIMESTAMP type has a proprietary auto-update feature, which will be described later.

TypeSize (Bytes)RangeFormatPurpose
DATE31000-01-01/9999-12-31YYYY-MM-DDYear, month, day
TIME3'-838:59:59'/'838:59:59'HH:MMHour, minute, second
YEAR11901/2155YYYYYear value
DATETIME81000-01-01 00:00:00/9999-12-31 23:59:59YYYY-MM-DD HH:MMYear, month, day, hour, minute, second
TIMESTAMP41970-01-01 00:00:00/2038 ends at 2147483647 seconds, Beijing time 2038-1-19 11:14:07, Greenwich time January 19, 2038, 03:14:07YYYYMMDD HHMMSSMixed date and time value, timestamp
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 example
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)

# Inserting null will automatically insert the current time
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)

# Adding a column with a default value of '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

# Manually modify the new column's default value to the current time
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 example
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)
# The lower limit of timestamp time is 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)
# The upper limit of timestamp time is 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 example 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 example
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 example
String Types#

String types refer to CHAR, VARCHAR, BINARY, VARBINARY, BLOB, TEXT, ENUM, and SET. This section describes how these types work and how to use them in queries.

TypeSizePurpose
CHAR0-255 bytesFixed-length string
VARCHAR0-65535 bytesVariable-length string
TINYBLOB0-255 bytesBinary string not exceeding 255 characters
TINYTEXT0-255 bytesShort text string
BLOB0-65,535 bytesLong text data in binary format
TEXT0-65,535 bytesLong text data
MEDIUMBLOB0-16,777,215 bytesMedium-length text data in binary format
MEDIUMTEXT0-16,777,215 bytesMedium-length text data
LONGBLOB0-4,294,967,295 bytesExtremely large text data in binary format
LONGTEXT0-4,294,967,295 bytesExtremely large text data

CHAR and VARCHAR types are similar, but they differ in how they store and retrieve data. Their maximum lengths and whether trailing spaces are preserved also differ. No case conversion is performed during storage or retrieval.

The length of a CHAR column is fixed to the length declared when the table is created, ranging from (0-255); while the value of VARCHAR is a variable-length string ranging from (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)

# When retrieving, the char data type will remove spaces
mysql> select * from t9;
+------+------+ 
| v    | c    | 
+------+------+ 
| ab   | ab   | 
+------+------+ 
1 row in set (0.00 sec)

# Let's take a look at the length of the calculated query results
mysql> select length(v),length(c) from t9;
+-----------+-----------+ 
| length(v) | length(c) | 
+-----------+-----------+ 
|         4 |         2 | 
+-----------+-----------+ 
1 row in set (0.00 sec)

# Adding a plus sign to the result will make it clearer
mysql> select concat(v,'+'),concat(c,'+') from t9;
+---------------+---------------+ 
| concat(v,'+') | concat(c,'+') | 
+---------------+---------------+ 
| ab  +         | ab+           | 
+---------------+---------------+ 
1 row in set (0.00 sec)

# When the stored length exceeds the defined length, it will be truncated
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 example

BINARY and VARBINARY are similar to CHAR and VARCHAR, but they contain binary strings rather than non-binary strings. This means they contain byte strings rather than character strings. This indicates that they have no character set, and sorting and comparison are based on the numeric values of the column values.

BLOB is a binary large object that can hold a variable amount of data. There are four types of BLOB: TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. They differ in the amount of storage they can accommodate.

There are four types of TEXT: TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to the four types of BLOB, with different maximum lengths that can be selected based on actual conditions.

ENUM and SET Types#

ENUM, known as the enumeration type in Chinese, requires its value range to be explicitly specified through enumeration when creating the table. ENUM only allows selecting a single value from the set of values and cannot select multiple values at once.

SET is very similar to ENUM; it is also a string object that can contain 0-64 members. Depending on the members, the storage also varies. The SET type allows selecting one or more elements from the set of values. Content that exceeds the range will not be allowed to be injected, and duplicate values will be automatically deduplicated.

TypeSizePurpose
ENUMRequires 1 byte to store for 1-255 members; requires 2 bytes for 255-65535 members; allows a maximum of 65535 members.Single choice: selecting gender
SET1-8 members occupy 1 byte; 9-16 members occupy 2 bytes; 17-24 members occupy 3 bytes; 25-32 members occupy 4 bytes; 33-64 members occupy 8 bytes.Multiple choice: hobbies

set/enum example

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

# Select one of enum('female','male') as the value for gender, can insert normally
mysql> insert into t10 values ('nezha','male');
Query OK, 1 row affected (0.00 sec)

# Cannot insert both 'male,female' at the same time, nor can it insert values not belonging to '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('smoking','drinking','haircut','crash'));
Query OK, 0 rows affected (0.01 sec)

# Can arbitrarily choose items from set('smoking','drinking','haircut','crash'), and has deduplication function
mysql> insert into t11 values ('yuan','haircut,drinking,haircut');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t11;
+------+---------------+ 
| name | hobby        | 
+------+---------------+ 
| yuan | drinking,haircut | 
+------+---------------+ 
1 row in set (0.00 sec)

# Cannot choose items not belonging to set('smoking','drinking','haircut','crash')
mysql> insert into t11 values ('alex','haircut,crash,looking at girls');
ERROR 1265 (01000): Data truncated for column 'hobby' at row 1

Table Constraints#

Set a number to be unsigned unsigned.

Restrict a field to not be null not null.

Set a default value for a field default.

Set a field to not be duplicated unique.

Set an int type field to auto-increment auto_increment.

Set a field to be non-null and unique primary key.

Foreign key foreign key.

Composite Unique#
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#

The auto-increment field must be a number and must be unique, automatically providing a non-null effect.

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#

A table can only have one primary key.

A table can have no primary key, but it is best to set one for each table.

Restrict this field to be non-null (not null) and unique (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)

The first non-null and unique field you specify will be defined as the primary key.

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)

Directly specifying primary key defaults to non-null and unique.

Composite Primary Key#
create table t8(
    id int,
    ip char(15),
    server char(10),
    port int,
    primary key(ip,port)
);
Foreign Key Involving Two Tables#

Employee Table

id age gender salary hire_date postid

Department Table

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 department','good team','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>

The foreign key must relate to at least one primary key. Note: Create the referenced table before creating the foreign key table, for example, create the department table first and then the employee table.

Cascading Delete and Update 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 (understanding)

. cascade method
When updating/deleting records on the parent table, the matching records in the child table are updated/deleted synchronously.

   . set null method
When updating/deleting records on the parent table, the matching records in the child table are set to null.
Note that the foreign key column in the child table cannot be not null.

   . No action method
If there are matching records in the child table, updating/deleting operations on the corresponding candidate key in the parent table are not allowed.

   . Restrict method
Same as no action, both immediately check foreign key constraints.

   . Set default method
When changes occur in the parent table, the foreign key column in the child table is set to a default value, but Innodb cannot recognize it.

Modify Table#

Syntax:

  1. Rename table
    ALTER TABLE table_name
    RENAME new_table_name;

  2. Add field
    ALTER TABLE table_name
    ADD field_name data_type [integrity constraint…],
    ADD field_name data_type [integrity constraint…];

  3. Drop field
    ALTER TABLE table_name
    DROP field_name;

  4. Modify field
    ALTER TABLE table_name
    MODIFY field_name data_type [integrity constraint…];
    ALTER TABLE table_name
    CHANGE old_field_name new_field_name old_data_type [integrity constraint…];
    ALTER TABLE table_name
    CHANGE old_field_name new_field_name new_data_type [integrity constraint…];

  5. Modify field order/Specify field position when adding
    ALTER TABLE table_name
    ADD field_name data_type [integrity constraint…] FIRST;
    ALTER TABLE table_name
    ADD field_name data_type [integrity constraint…] AFTER field_name;
    ALTER TABLE table_name
    CHANGE field_name old_field_name new_field_name new_data_type [integrity constraint…] FIRST;
    ALTER TABLE table_name
    MODIFY field_name data_type [integrity constraint…] AFTER field_name;

Table Relationships#

Relationships between two tables

Many-to-One

===================== Many-to-One =====================
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
('Beijing Industrial Mine Publishing House'),
('People's Music Not Good Publishing House'),
('Intellectual Property Useless Publishing House')
;

insert into book(name,press_id) values
('Nine Yang Divine Skill',1),
('Nine Yin Manual',2),
('Nine Yin White Bone Claw',2),
('Dugu Nine Swords',3),
('Dragon Ten Palms',2),
('Kite Flower Manual',3)
;

sql example

One-to-One

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, # This field must be unique
    -> foreign key(customer_id) references customer(id) # The foreign key field must ensure uniqueness
    -> on delete cascade
    -> on update cascade
    -> );

# Add customers
mysql> insert into customer(name,qq,phone) values
    -> ('Han Lei','31811231',13811341220),
    -> ('Yang Lan','123123123',15213146809),
    -> ('Weng Huitian','283818181',1867141331),
    -> ('Yang Zonghe','283818181',1851143312),
    -> ('Yuan Chengming','888818181',1861243314),
    -> ('Yuan Qing','112312312',18811431230)

mysql> # Add students
mysql> insert into student(class_name,customer_id) values
    -> ('Full-time Class 1',3),
    -> ('Weekend Class 1',4),
    -> ('Weekend Class 1',5)
    -> ;
sql example

Many-to-Many

===================== Many-to-Many =====================
create table author(
id int primary key auto_increment,
name varchar(20)
);


# This table stores the relationship between the author table and the book table, i.e., querying the relationship between the two can be done through this table
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)
);


# Insert four authors, with ids arranged sequentially
insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq');

# Each author has their representative works as follows
egon: 
Nine Yang Divine Skill
Nine Yin Manual
Nine Yin White Bone Claw
Dugu Nine Swords
Dragon Ten Palms
Kite Flower Manual
alex: 
Nine Yang Divine Skill
Kite Flower Manual
yuanhao:
Dugu Nine Swords
Dragon Ten Palms
Kite Flower Manual
wpq:
Nine Yang Divine Skill


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 example

Data Operations#

Add insert#

insert into table_name values (values...); All fields in this table must be filled in order.

insert into table_name (field_name, field_name...) values (values...); All fields with specified names must correspond one-to-one with the values that follow.

insert into table_name value (values...); Can only write one row of data at a time; values can write multiple rows at once.

Delete delete#

delete from table where condition;

Modify update#

update table set field=new value where condition;

Query select#

select * from table_name; select field from table_name;

Remove duplicates: select distinct field from table_name;

Arithmetic operations: select field*10 from table_name; You can also rename the name after the arithmetic operation: select field*10 as new_name from table_name; or omit as and keep the space.

Where Clause#

Comparison Operations#

> < = >= <= != <> (also means not equal to)

Range Operations#

​ Choose one from multiple options in

select * from table_name where field_name in (value1,value2,value3);

​ In a fuzzy range

​ In a numerical interval [a,b] between

select * from table_name where field_name between a and b;

​ Fuzzy string query like

​ Wildcard % matches any length of any content

select * from table_name where field_name like 'fuzzy character%';

​ Wildcard _ matches a single character length of any content; add as many _ as needed.

select * from table_name where field_name like 'fuzzy character__';

​ Regular matching regexp

select * from table_name where field_name regexp 'regular expression';

Logical Operations - Condition Combination#

And and Or or Not not

Grouping group by#

select * from table_name group by field;

This will keep each different item in the field after group by and group all values of this item together.

Aggregation#

count(field) counts how many items are in this field select count(*) from table_name;

sum(field) counts the sum of the values corresponding to this field.

avg(field) counts the average value corresponding to this field.

min(field) counts the minimum value corresponding to this field.

max(field) counts the maximum value corresponding to this field.

Group Aggregation#

select count(*) from table_name group by field;

select sum(field) from table_name group by field;

Filtering having#

Having is always used with group by.

select field from table_name group by field_name having condition;

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

Query Sorting order by#

select * from table_name order by field_name; Defaults to ascending order, default is asc, can be omitted.

select * from table_name order by field_name desc; Sort in descending order.

Multi-column sorting: select * from table_name order by field_name1 asc, field_name2 desc; You can specify the first field to be sorted in ascending order, and then sort the second field in descending order when the first field is the same.

Limit the Number of Records Returned limit#

select * from table_name order by field_name desc limit how many top values;

Paging operation

select * from table_name order by field_name desc limit 0,5; Start from 0 and take the first 5 values.

select * from table_name order by field_name desc limit 5,5; Start from 5 and take the next 5.

limit m,n is equivalent to limit n offset m

Their order cannot change: select distinct columns to display from table where condition group by grouping having filtering group condition order by sorting limit top n rows.

Regular Query#

If you accidentally hit enter, you can use \c to exit.

Operating data on a Linux server:

Connect to the MySQL database

C:\Users\HP>mysql -uwanlx -pwanlx -h139.196.217.70 -P8098
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 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.

View databases

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)

Enter the database

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

View tables

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

View table structure

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)

View table content

mysql> select * from StuInfo;
+----+--------+-----------------------+------+--------------------+ 
| id | name   | class                 | age  | address            | 
+----+--------+-----------------------+------+--------------------+ 
|  1 | Wan Lixia | Class 2 of 09 Automation |   31 | Fenyi County, Xinyu City, Jiangxi Province | 
|  2 | Tang Qinghua | Class 1 of 17 Automation |   20 | Ganzhou City, Jiangxi Province | 
|  3 | Zhang San | Class 1 of 19 Automation |   21 | Ganzhou City, Jiangxi Province | 
|  4 | Li Si | Class 1 of 17 Automation |   22 | Ganzhou City, Jiangxi Province | 
|  5 | Huang Shihai | Class 1 of 19 Internet of Things Engineering Undergraduate |   22 | Jiujiang City, Jiangxi Province | 
|  6 | Jia Jingqi | Class 2 of 19 Internet of Things Engineering Undergraduate |   22 | Yuncheng City, Shanxi Province | 
|  7 | Yan Gan | Class 2 of 19 Internet of Things Engineering Undergraduate |   22 | Ganzhou City, Jiangxi Province | 
|  8 | Tang Wenxi | Class 1 of 19 Automation |   22 | Ganzhou City, Jiangxi Province | 
+----+--------+-----------------------+------+--------------------+ 
8 rows in set (0.08 sec)

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.