数据库系统概念第六版 第五章练习题 2 4
5.2
写一个使用JDBC元数据特性的JAVA函数,该函数用ResultSet作为输入参数,并把结果输出为用合适的名字作为列名的表格形式。
(对JAVA不太熟悉,仿照着书上的代码写的)
ResultSetTable(ResultSet result)
{
ResultSetMetaData metadata = result.getMetaData();
int num_cols = metadata.getColumnCount();
for(int i = 1; i <= num_cols; i++)
{ //打印表头和Type信息
System.out.print(metadata.getColumnName(i));
System.out.print(metadata.getColumnTypeName(i))
}
System.out.println();
while(result.next()!=NULL)
{
for(int i = 1; i <= num_cols; i++)
{ //打印每行信息
System.out.print(result.getString(metadata.getColumnName(i)‘));
}
System.out.println();
}
}
5.4
说明如何用触发器来保证约束"一位教师不可能在一个学期的同一时间段在不同的教室教课"。(要知道,对关系teaches的或section的改变都可能使该约束被破坏)
这个题做起来非常困难。每次完成时总会发现某一个环节出了问题需要推倒重来,花费了非常长的时间。
create trigger teaches_trigger after insert或update on teaches --插入和更新都可能引起改变
referencing new row as nrow
for each row
begin
--筛选出该课程的教室和时间段
select building as bd1,time_slot_id as tid,room_number as rn1
from section
where (section.course_id=nrow.course_id and section.sec_id=nrow.sec_id and section.semester=nrow.semester and section.year=nrow.year);
--筛选出该老师在这一学年的同一时间段的课程信息
select teaches.sec_id as sid, section.building as bd2, section.room_number as rn2,
from teaches natural join section
where (teaches.ID=nrow.ID and section.time_slot_id=tid and section.semester=nrow.semester and section.year=nrow.year );
--如果此老师在同一年的同一学期的相同时间段已排了一门课,新插入的课如果想同时间段必须保证教室相同且sec_id不同。
if (bd1!=bd2 or rn1!=rn2)
rollback;
else if sid=nrow.sec_id
rollback;
end
create trigger section_trigger after insert或update on section --插入和更新都可能引起改变
referencing new row as nrow
for each row
begin
--筛选出该课程的教室和时间段
select building as bd1,time_slot_id as tid,room_number as rn1
from nrow ;
--用with筛选出该课程对应的teaches信息
--再筛选出该老师在这一学年的同一时间段的课程信息
select teaches.sec_id as sid, section.building as bd2, section.room_number as rn2,
from teaches natural join section
where (section.time_slot_id=tid and section.semester=nrow.semester and section.year=nrow.year and teaches.ID=(select ID from nrow natural join teaches));
--如果此老师在同一年的同一学期的相同时间段已排了一门课,新插入的课如果想同时间段必须保证教室相同且sec_id不同。
if (bd1!=bd2 or rn1!=rn2)
rollback;
else if sid=nrow.sec_id
rollback;
end