MySQL的简单实用 手把手教学


MySQL的使用

1.登陆数据库

打开terminal

在终端根文件目录下输入/usr/local/mysql/bin/mysql -u root -p

接着输入管理员密码

截屏2020-10-09 07.39.56

2.显示所有的数据库

输入:

mysql> SHOW DATABASES;

(不要忘记加 ‘ ; ’ ,在mysql中分号为一句语句的结束)

显示结果:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| studb              |
| sys                |
+--------------------+
5 rows in set (0.06 sec)

3.使用数据库

在上面的显示的数据库中,使用studb数据库,输入:

mysql> USE studb;

若没有创建过数据库,则可以使用以下命令来创建数据库:

mysql> CREATE DATABASE studb;

4.展示数据库中所有的表

输入:

mysql> SHOW TABLES;

显示结果:

+-----------------+
| Tables_in_studb |
+-----------------+
| student         |
+-----------------+
1 row in set (0.00 sec)

可以看到数据库有一张表,若没有创建表,则可以使用下面的命令创建:

mysql> CREATE TABLE student(
	->stu_id             INT            PRIMARY KEY      NOT NULL,
	->stu_name            CHAR(25)            NOT NULL,
  	->stu_email            CHAR(25)            NULL,
  	->stu_address            CHAR(50)            NULL);

5.打印表的结构

输入:

mysql> DESC student;

显示结果:

+-------------+----------+------+-----+---------+-------+
| Field       | Type     | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+-------+
| stu_id      | int      | NO   | PRI | NULL    |       |
| stu_name    | char(25) | NO   |     | NULL    |       |
| stu_email   | char(25) | YES  |     | NULL    |       |
| stu_address | char(50) | YES  |     | NULL    |       |
+-------------+----------+------+-----+---------+-------+
4 rows in set (0.00 sec)

6.向表中插入数据

输入:

mysql> INSERT INTO student(stu_id, stu_name, stu_email, stu_address)
    -> VALUES(2020100116,'张三','zhangsan@163.com','beijin');

7.查看表中数据

输入:

mysql> SELECT *
		-> FROM student;

显示结果:

+------------+----------+------------------+-------------+
| stu_id     | stu_name | stu_email        | stu_address |
+------------+----------+------------------+-------------+
| 2020100116 | 张三     | zhangsan@163.com | beijin      |
+------------+----------+------------------+-------------+
1 row in set (0.00 sec)

8.修改表中的数据

输入:

mysql> UPDATE student 
		-> SET stu_email = 'nbplus@qq.com' 
		-> WHERE stu_id = 2020100116;

更新成功后,查看更新结果:

mysql> SELECT stu_id, stu_name, stu_email
		-> FROM student
		-> WHERE stu_id = 2020100116;

显示结果:

+------------+----------+---------------+
| stu_id     | stu_name | stu_email     |
+------------+----------+---------------+
| 2020100116 | 张三     | nbplus@qq.com |
+------------+----------+---------------+
1 row in set (0.00 sec)

9.删除表中的数据

输入:

mysql> DELETE FROM student WHERE stu_id = 2020100116;

------------恢复内容结束------------

相关