首页 > 编程笔记 > MySQL笔记 阅读:2

MySQL数据的增删改查(附带实例)

MySQL 是一个关系数据库管理系统(Relational Database Management System, RDBMS),是非常流行的关系数据库管理系统之一。

本节带领读者掌握使用 SQL 对数据表中的数据进行增删改查。

MySQL插入数据

MySQL 数据表使用 INSERT INTO 语句来插入数据。语法为:
NSERT INTO table_name(field1,field2,…,fieldN) VALUES(value1,value2,…,valueN)
如果数据是字符型,则必须使用单引号或者双引号,如"value"。

实例如下:
# 向 test_tbl 数据表插入两条数据
mysql> INSERT INTO test_tbl
    ->      (test_code, test_name, test_date)
    ->      VALUES
    ->      ("MySQL数据库1", "test001", NOW());
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> INSERT INTO test_tbl
    ->      (test_code, test_name, test_date)
    ->      VALUES
    ->      ("MySQL数据库2", "test002", NOW());
Query OK, 1 row affected, 1 warning (0.00 sec)

MySQL查询数据

MySQL 数据表使用 SELECT 命令来查询数据,语法为:
SELECT column_name, column_name FROM table_name [WHERE clause] [LIMIT N] [OFFSET M]
实例如下:
# 返回数据表test_tbl的所有记录
mysql> SELECT * FROM test_tbl;
+---------+-----------------+-----------+------------+
| test_id | test_code       | test_name | test_date  |
+---------+-----------------+-----------+------------+
|       1 | MySQL数据库1    | test001   | 2023-08-14 |
|       2 | MySQL数据库2    | test002   | 2023-08-14 |
+---------+-----------------+-----------+------------+
2 rows in set (0.00 sec)
实例解析如下:

MySQL更新数据

MySQL 数据表的数据可以使用 UPDATE 命令进行修改或更新。语法为:
UPDATE table_name SET field1 = new-value1, field2 = new-value2 [WHERE clause]
实例如下:
# 更新数据表中test_id 为 1 的 test_name 字段值为test001_update
mysql> UPDATE test_tbl SET test_name = 'test001_update' WHERE test_id = 1;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 0
mysql> SELECT * FROM test_tbl;
+---------+-----------------+----------------+------------+
| test_id | test_code       | test_name      | test_date  |
+---------+-----------------+----------------+------------+
|       1 | MySQL数据库1    | test001_update | 2023-08-14 |
|       2 | MySQL数据库2    | test002        | 2023-08-14 |
+---------+-----------------+----------------+------------+
2 rows in set (0.00 sec)

MySQL删除数据

MySQL 数据表的数据可以使用 DELETE 命令进行删除。删除数据时必须十分谨慎,因为执行删除命令后数据会被清空。语法为:
DELETE FROM table_name [WHERE clause]
若没有指定 WHERE 子句,MySQL 数据表中的所有记录将被删除。WHERE 子句中可以指定任何条件。

实例如下:
# 删除 test_tbl 数据表中 test_id 为2 的记录
mysql> DELETE FROM  test_tbl WHERE test_id  = 2;
Query OK, 1 row affected (0.00 sec)
mysql> SELECT * FROM test_tbl;
+---------+-----------------+----------------+------------+
| test_id | test_code       | test_name      | test_date  |
+---------+-----------------+----------------+------------+
|       1 | MySQL数据库1    | test001_update | 2023-08-14 |
+---------+-----------------+----------------+------------+
1 row in set (0.01 sec)

相关文章