Home > Database > Mysql Tutorial > 让你提前认识软件开发(33):数据操纵语言(DML)

让你提前认识软件开发(33):数据操纵语言(DML)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 15:58:08
Original
1261 people have browsed it

第2部分 数据库SQL语言 数据操纵语言(DML) 数据操纵语言(Data Manipulation Language, DML )包括insert、delete和update语句,用于增、删、改数据。 本文用以下的表tb_employeeinfo作为例子加以说明: create table tb_employeeinfo ( employeeno varchar(2

第2部分 数据库SQL语言

数据操纵语言(DML)

 

数据操纵语言(Data Manipulation Language,DML)包括insert、delete和update语句,用于增、删、改数据。

本文用以下的表tb_employeeinfo作为例子加以说明:

create table tb_employeeinfo

(

employeeno varchar(20) not null, -- 员工工号

employeename varchar(20) not null, -- 员工姓名

employeeage int null -- 员工年龄

);

在实际的软件开发项目中,DML的使用规则如下:

1. insert语句必须列出字段名

许多开发人员为了省事,在需要向一个表中所有字段都插入数据的时候,就直接列出表名即可,如下所示:

反例:

insert into tb_employeeinfo vaues(‘10000’,’Jim’, 30)

这样,如果tb_employeeinfo表结构发生了修改,以前的SQL语句就不能写入数据了。正确的做法是不管向表中多少个字段插入数据,都需要列出字段名。如下所示:

正例:

insert into tb_employeeinfo(employeeno, employeename, employeeage) vaues(‘10000’,’Jim’, 30)

同样,不要使用“select * from”语句,必须列出字段名,即使是返回所有字段的值。

 

2. delete,update语句必须带where条件

这样做是为了防止将整个表的数据修改和清空,导致系统瘫痪。对于全表处理,则使用“where 1=1”。

正例:

delete from tb_employeeinfo where employeeage=30

update tb_employeeinfo set employeeage=32 where 1=1

3. SQL语句块或存储过程中需要对DML语句的执行结果进行检查

这是数据库的错误/异常处理机制,需要对SQL语句执行成功或失败进行检查,以便根据执行结果决定后续的操作。

(1) SQLServer/Sybase数据库的处理

在SQLServer/Sybase数据库中,可以通过系统变量“@@error”来检查,并根据结果进行处理,如果已经开始了事务(数据库的修改是以事务为单位进行的。一个事务就是一个操作序列,这些操作要么全做,要么全不做,它是一个不可分割的工作单位),则需要进行回滚。

正例:

begin tran -- 事务开始

insert into ……

if @@error 0

begin

rollback tran -- 事务回滚

return

end

update ……

if @@error 0

begin

rollback tran -- 事务回滚

return

end

commit tran -- 事务提交

(2) Oracle数据库的处理

在Oracle中,错误是通过异常机制进行处理的。如果没有异常处理部分,它会立即中止当前的SQL语句块,并自动进行回退。如果需要根据情况进行处理,就应该使用异常处理部分,否则使用Oracle缺省的行为中止当前的SQL块,并自动回退。

正例1:

begin

insert into …

update …

insert into…

exception

when others then

begin

…… -- 错误处理

rollback;

end;

end;

正例2:

begin

insert into …

update …

insert into… -- 没有异常处理部分

end;

此外,在SQL语句块和存储过程中使用事务,必须保证事务的开始与结束匹配,即必须保证在SQL语句块的任何分支和异常情况下“begin tran”都有正确的“commit”或“rollback”与之对应。

在实际的软件项目中,数据操纵语言(DML)使用的非常的广泛,正确地使用该语言是对一个软件开发人员的基本要求。 

(本人微博:http://weibo.com/zhouzxi?topnav=1&wvr=5,微信号:245924426,欢迎关注!)

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template