DML(Data Manipulation Language),指数据操作语言,用来对数据库中表的数据记录进行更新。插入insert、删除delete、更新update。
数据插入
第一种:在对应的列名中插入相应的值。所以要注意列名的数量和值的数量相同,且一一对应。
insert into 表 (列名1,列名2,列名3...) values (值1,值2,值3...);
第二种:向表中所有列插入
insert into 表 values (值1,值2,值3...);
代码示意:
-- 创建数据库
create database if not exists mydb1 ; #不存在的话创建
use mydb1; #使用myds1数据库
-- 创建一个student表
create table if not exists student(
sid int,
name varchar(20), #varchar(20)表示字符串最长20个
gender varchar(20),
age int,
birth date,
address varchar(20),
score double
);
-- 数据的插入
-- 方式一:insert into 表 (列名1,列名2,列名3...) values (值1,值2,值3...);
-- 注意一定要一一对应
insert into student(sid,name,gender,age,birth,address,score)
values(1001,'张思','男',18,'1996-12-23','北京',83.5);
-- 也可以一次性插入多行
insert into student(sid,name,gender,age,birth,address,score)
values (1002,'小红','女',18,'1996-2-23','西藏',87.5),
(1003,'小白','女',18,'1996-12-2','江苏',83.5),
(1004,'小王','男',18,'1996-1-2','新疆',80.5);
-- 方式二:insert into 表 values (值1,值2,值3...);
-- 可以只插入一行,也可以插入多行,多行用逗号分开
insert into student values (1005,'小朱','男',18,'1996-6-7','新疆',89.5),
(1006,'小皮','男',18,'1996-6-7','四川',92.5);
修改数据
第一种:直接修改所有行的数据
update 表名 set 字段名=值,字段名=值... ;
第二种:对指定位置进行修改
update 表名 set 字段名=值,字段名=值... where 条件 ;
举例:
-- 将所有学生的地址修改为重庆
update student set address = '重庆’;
-- 将sid为1004的学生的地址修改为北京
update student set address = '北京' where sid = 1004
-- 将sid为1005的学生的地址修改为北京,成绩修成绩修改为100
update student set address = '广州',score=100 where sid = 1005
数据删除
语法1:
delete from 表名 [where 条件];
语法2:
truncate table 表名 或者 truncate 表名
和前面的drop
不一样,drop
一般不涉及数据的内容,直接删库,,涉及具体内容一般用delete
例子:
-- 1.删除sid为1004的学生数据
delete from student where sid = 1004;
-- 2.删除表所有数据
delete from student;
-- 3.清空表数据
truncate table student;
truncate student;
truncate table student;
truncate student;truncate的效果和delete一样,但是原理不同,更加彻底。
delete只删除内容,而truncate类似于drop table ,可以理解为是将整个表删除,然后再创建该表;
总结
声明:内容来源于B站视频《2022黑马程序员最新MySQL知识精讲+mysql实战案例_零基础mysql数据库入门到高级全套教程》,博客内容仅作学习参考使用。