数据库系统概念CH5
5.1 使用程序设计语言访问数据库
JDBC和ODBC
JDBC标准定义了Java程序连接数据库服务器的应用程序接口(API)
通过JDBC的API可以实现:
- 连接到数据库
- 向数据库系统中传递SQL语句
- 获取查询结果
ODBC(开放数据库互连)标准定义了一个API使得应用程序可以通过它打开一个数据库连接、发送查询和更新以及返回结果等。
5.2函数和过程
声明和调用SQL函数和过程
函数:
需要用到的变量可以通过declare语句进行声明,可以是任意的合法SQL类型,用set语句进行赋值
-------------------------------------------------------------------
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
--------------------------------------------------------------------
create function instructors_of (dept_name char(20))
returns table ( ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept_name = instructors_of.dept_name)
过程:
create procedure dept_count_proc (in dept_name varchar(20), out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_count_proc.dept_name
end
过程中的 in 和 out 分别表示待赋值的参数和为返回结果而在过程中设置值的参数
SQL支持while语句和repeat语句,均表示循环.用法:
declare n integer default 0;
while n < 10 do
set n = n + 1
end while
repeat
set n = n – 1
until n = 0
end repeat
for循环和if-then-else条件判断语句
declare n integer default 0;
for r as
select budget from department
where dept_name = ‘Music’
do
set n = n + r.budget
end for
if 布尔表达式
then 语句
elseif 布尔表达式
then 语句
else 语句
end if
5.3 Trigger触发器
触发器是一个语句,当对数据库做修改时,它会被系统自动执行。
触发器机制的设置两个条件:指明什么条件下执行触发器以及引起触发器时的动作
create trigger timeslot_check1 after insert on section
referencing new row as nrow
for each row
when (nrow.time_slot_id not in (
select time_slot_id
from time_slot)) /* time_slot_id not present in time_slot */
begin
rollback
end;
触发器可以设置在插入删除更新时使用,分别如下:
after update of takes on grade
referencing old row as : for deletes and updates
referencing new row as : for inserts and updates