语句 | 功能 |
---|---|
INSERT | 插入 |
UPDATE | 修改 |
DELETE | 删除 |
(1)DML
(Data Manipulation Language – 数据操纵语言
) 可以在下列条件下执行:
– 向表中插入数据
– 修改现存数据
– 删除现存数据
(2)事务是由完成若干项工作的DML语句
组成的
使用 INSERT 语句向表中插入数据:
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);
使用这种语法一次只能向表中插入一条数据
2、插入数据
• 为每一列添加一个新值。
• 按列的默认顺序列出各个列的值。
• 在 INSERT 子句中随意列出列名和他们的值。
•字符和日期型数据应包含在单引号中。
INSERT INTO departments(department_id, department_name,
manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);
1 row created.
INSERT INTO
employees(employee_id,last_name,email,hire_date,job_id)
VALUES (300,’Tom’,’tom@126.com’,to_date(‘2012-3-
21’,’yyyy-mm-dd’),’SA_RAP’);
1 row created.
3、向表中插入空值
(1)隐式方式: 在列名表中省略该列的值
INSERT INTO departments (department_id,
department_name )
VALUES (30, 'Purchasing');
1 row created.
(2)显示方式: 在VALUES 子句中指定空值
INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);
1 row created.
4、插入指定的值
NOW()函数:记录当前系统的日期和时间
INSERT INTO employees (employee_id,
first_name, last_name,
email, phone_number,
hire_date, job_id, salary,
commission_pct, manager_id,
department_id)
VALUES (113,
'Louis', 'Popp',
'LPOPP', '515.124.4567',
NOW(), 'AC_ACCOUNT', 6900,
NULL, 205, 100);
1 row created.
5、从其它表中拷贝数据
在 INSERT 语句中加入子查询:
INSERT INTO emp2
SELECT *
FROM employees
WHERE department_id = 90;
3 rows created.
INSERT INTO sales_reps(id, name, salary, commission_pct)
SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';
4 rows created.
注意:
(1)不必书写 VALUES 子句
(2)子查询中的值列表应与 INSERT 子句中的列名对应
(1)使用 UPDATE 语句更新数据
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
(2)可以一次更新多条数据。
(3)如果需要回滚数据,需要保证在DML前,进行设置:SET AUTOCOMMIT = FALSE;
2、更新数据
(1)使用 WHERE 子句指定需要更新的数据
UPDATE employees
SET department_id = 70
WHERE employee_id = 113;
1 row updated.
(2)如果省略 WHERE 子句,则表中的所有数据都将被更新
UPDATE copy_emp
SET department_id = 110;
22 rows updated.
3、更新中的数据完整性错误
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
DEPARTMENTS:
从表DEPARTMENTS 中删除一条记录
1、DELETE 语句
使用 DELETE
语句从表中删除数据
DELETE FROM table
[WHERE condition];
2、删除数据
(1)使用 WHERE
子句删除指定的记录
DELETE FROM departments
WHERE department_name = 'Finance';
1 row deleted.
(2)如果省略 WHERE 子句,则表中的全部数据将被删除
DELETE FROM copy_emp;
22 rows deleted.
3、删除中的数据完整性错误
DELETE FROM departments
WHERE department_id = 60;
#错误代码: 1451
Cannot delete or update a parent row: a foreign key
constraint fails (`myemployees`.`employees`,
CONSTRAINT `dept_id_fk` FOREIGN KEY (`department_id`)
REFERENCES `departments` (`department_id`))
#原因:
You cannot delete a row that contains a primary key that is used as a
foreign key in another table.