2006年9月9日

          Manager User

          create user test1 identified by test1;
          grant connect,create table to test1;
          conn cyts_cc/cyts_cc@orcl2000;
          create table(
          id int)
          tablespace user;
          ERROR 位于第 1 行:
          ORA-01950: 表空間'USERS'中無權限
          conn cyts_cc/cyts_cc@orcl2000;
          alter user test1 quota 1M on users;
          create tab
          (id int);
          success
          alter user test1 account lock;
          conn test1/test1@orcl2000;
          ERROR:
          ORA-28000: the account is locked
          1 Database Schema
          ?a schema is a named collection of objects
          ?b user is created and a corresponding schema is created
          ?c user can be associated only with one schema
          ?d username and schema are often userd interchangely.
          2 Checklist for creating users
          ? a idntfigy tablespaces in which the usr nedds to store objects
          ? b decide on quotas for each tablespace
          ? c assign a default tablespace and temporary tablespace.if you do not specify at the time of create user,system tablespace will be the defalut tablespace and temporary.it will affect the performance of the oralce.
          ? d create user
          ? e grant privileges and roles to user
          ? desc dba_users;
          ? select * from dba_users;
          3 Creating a new user:
          Database Authentiacation
          ?set the initial password
          ? create user aaron
          ? identified by soccer
          ? default tablespace data
          ? temporary tablespace temp
          ? guota 15m on data
          ? password expire;

          ? alter database default temporary tablespace temp;
          4 Creating a new user operating System Authentication
          ? os_authent_prefix initialllization parameter specifies the format of the username
          ? defauts to ops$
          ??? create user arron
          ??? identified externally
          ??? default tablespace users
          ??? temporary tablespace temp
          ??? quota 15m on data
          ??? password expire;

          ??? conn /
          ??? show parameter os
          ??? os_authent_prefix??????????????????? string?????????????????????????? OPS$
          ??? create user ops$test3
          ????? identified externally
          ????? default tablespace us
          ????? temporary tablespace
          ????? quota 10m on users
          ??? thee test2 is an user of os ,which the oracle is installed.
          5 Changing user quota on tablespace
          ?alter user test3 quota 4m on users;
          ?you cann't grant quota on temp and undotbs.
          ?
          ?alter quota 0 on uers -- means that no new table space can be allocated and cannot change the exist object in the tablespaces
          6 drop user
          ?you cannot drop user who has connected to oracle
          ? drop user (cascade)
          7 Obtaining User information
          ?information about uers can be obtained by qerying the data dictionary
          ? dba_users
          ? 名稱??????????????????????????
          -----------------------------
          USERNAME??????????????????????
          USER_ID???????????????????????
          PASSWORD??????????????????????
          ACCOUNT_STATUS????????????????
          LOCK_DATE?????????????????????
          EXPIRY_DATE???????????????????
          DEFAULT_TABLESPACE????????????
          TEMPORARY_TABLESPACE??????????
          CREATED???????????????????????
          PROFILE???????????????????????
          INITIAL_RSRC_CONSUMER_GROUP???
          EXTERNAL_NAME?????????????????
          ? dba_ts_quotas
          ?? 名稱??????????
          ?---------------
          ?TABLESPACE_NAME
          ?USERNAME??????
          ?BYTES?????????
          ?MAX_BYTES?????
          ?BLOCKS????????
          ?MAX_BLOCKS????

          posted @ 2006-10-12 09:49 康文 閱讀(387) | 評論 (0)編輯 收藏

          Using SET Operators.

          1 The Union Operator
          ?The union operator returns results form both queries after eliminating duplications.\
          ?select employee_id,job_id
          ?from employees
          ?uniion
          ?select employ_id ,job_id
          ?from job_history;
          2 the all operator
          ?The union all opertor reutrn result from both queries,including all duplications
          3 interset
          ?select ster_id,qty from sales where qty>20;
          ?intersect
          ?select ster_id,qty from sales where ster_id like '7%';
          4 minus
          ?select ster_id,qty from sales where qty>20
          ?minus
          ?select ster_id from sales where ster_id like '7%'

          5 set operator guidelines
          ?. teh expressions in the select list must match in number and data type;
          ?. Parentheses can be used to alter the sequence of the execution
          ?.The order by clause:
          ??? can appear only at the very end of the statement
          ??? will accept the column name,aliases from thee firest select statement ,or thee positional notation
          ?.Duplicate row are atuomatically eliminated except in union all.
          ?.Column names from the first query appear in the result
          ?.The output is sorted in ascending order by default except in union all
          6 matching the select statement
          ?select department_id,to_number(null),location,hire_date
          ?from employees
          ?union
          ?select department_id,location_id,to_date(null)
          ?from departments;

          ?select employee_id,job_id,salary
          ?from employees
          ?union
          ?select employee_id,job_id,0
          ?from job_history;
          7 Controlling the order of the rows
          ?select 'sing' as "my dream" ,3,a_dummy
          ?from dual
          ?union
          ?select 'like''d like to teach',1
          ?from dual
          ?union
          ?select 'the world to',2
          ?from dual
          ?order by 2;

          posted @ 2006-10-11 14:51 康文 閱讀(225) | 評論 (0)編輯 收藏

          開發子過程

          ?1? 開發過程
          ?1) 建立過程:不帶參數
          ? create or replace procedure out_time
          ? is
          ? begin
          ??? dbms_output.put_line(systimestamp);
          ? end;
          ? a 使用execute 命令調用過程
          ?? set? serveroutput on
          ?? exec out_time;
          ? b 使用call 命令調用過程
          ?? set serveroutput on
          ?? call out_time();
          ?2) 建立過程:帶有in參數 默認為輸入參數,另外也可以使用in 關鍵子顯示的定義
          ?? create or replace procedure add_employee
          ?? (eno number,name varchar2,sal number,
          ??? job varchar default 'clerk',dno number)
          ?? is
          ?? e_integrity exception;
          ?? pragma exception_init(e_intgegrity,-2291);
          ?? begin
          ??? insert into emp(empno,ename,sal,job.deptno)
          ????? values(eno.name,sal,job,dno);
          ??? exception
          ????? when dup_val_on_index then
          ??????? raise_application_error(-20000,'雇員號不能重復');
          ????? when e_integrity then
          ??????? raise_application_error(-20001,'部門號不存在');
          ???
          調用
          ?? exec add_employee(111,'clark',200,'manager',10);
          ?? 3 建立過程,帶有out 參數
          ??? create or replcace procedure query_employee
          ??? (eno number,name out varchar2,salary out number)
          ??? is
          ??? begin
          ????? select ename,sal,into name,salary from emp where empno=eno;
          ??? exception
          ????? when no_data_found then
          ??????? raise_application_error(-20000,'G該雇員不存在');
          ??? end;
          ???
          ??? 調用
          ??? var name varchar2(10)
          ??? var salary number
          ??? exec query_employee(7788,:name,:salary);
          ??? print name,salary;
          ??? 4 建立過程,帶有in out 參數
          ??? create or replace procedure compute
          ??? (num1,in out number,num2 in out number)
          ??? is
          ?????? v1 number;
          ?????? v2 number;
          ??? begin
          ????? v1:=num1/num2;
          ????? v2:=mod(num1,num2);
          ????? num1:=v1;
          ????? num2:=v2;
          ??? end;?
          ???
          ??? 調用
          ??? var n1 number
          ??? var n2 number
          ??? exec :n1:=100;
          ??? exec :n2:=30
          ??? exec compute(:n1,:n2)
          ??? print n1 n2
          ??? 5) 為參數傳遞變量和數據 位置傳遞,名稱傳遞,組合傳遞
          ??? create or replace procedure add_dept
          ??? (dno number,dname varchar2 default null,loc varchar default null)
          ??? is
          ??? begin
          ????? insert into dept values(dno.dname,loc);
          ??? end;
          ??? -- 位置傳遞
          ???? exec add_dept(50,'sales','new york');
          ???? exec add_dept(60);
          ???? exec add_dept(70,'admin');
          ??? -- 名稱傳遞
          ???? exec add_dept(50,loc=>'new york');
          ???? exec add_dept(60,dname=>'sales',loc=>'new york');
          ?? 6) 顯示當前用戶的所有程序及其源代碼
          ???? select text from user_source where name='add_dept';
          ?? 7) 刪除過程
          ???? drop procedure add_dept;
          2 開發函數
          ? 可以在sql語句和其他子過程中執行。
          ? 1 建立函數,不帶任何參數
          ? create or replace function get_user
          ? return varchar2
          ? is
          ??? v_user varchar2(100);
          ? begin
          ??? select username into v_user from user_users;
          ??? return v_user;
          ??? end;
          ? --使用變量接收函數返回值
          ?? var v2 varchar2(100)
          ?? exec :v1:=get_user
          ?? print v1;
          ?-- 在sql 語句中直接調用函數
          ?? select get_user from dual;
          ?-- 使用dbms_output 調用函數
          ?? set serveroutput on
          ?? exec dbms_output.put_line('get_user');
          ?2) 建立函數,帶有in 參數
          ?? create or replace function get_sal(name in varchar2)
          ?? reutnr number
          ?? as
          ?? v_sal emp.sal%type;
          ?? begin
          ???? select sal into v_sal from emp where upper(ename)=upper(name);
          ???? return v_sal;
          ?? exception
          ???? when no_data_found then
          ?????? raise_application_error(-20000,'employee does not exist');
          ?? end;
          ?3) 建立函數,帶有out 參數
          ?? create or replace function get_info
          ?? (name varchar2,title out varchar2)
          ?? return varchar2
          ?? as
          ???? deptname dept.dname%type;
          ?? begin
          ???? select a,job,b,dname into title,deptname from emp a,dept b
          ???? where a.deptno=b.deptno
          ???? and upper(a.ename)=uppder(name);
          ???? return deptname;
          ?? end;
          ?? var job varchar2(20)
          ?? var dname varchar2(20)
          ?? exec :dname:=get_info('scott',job);
          ?? print dname job

          ?4) 帶有 in out 參數
          ? create or replace function result
          ? (num1,number,num2 in out nu8mber)
          ? return number
          ? as
          ??? v_result number(6);
          ??? v_remainder number;
          ? begin
          ??? v_result:=num1/num2;
          ??? v_remainder:=mod(num1,num2);
          ??? num2:=v_remainder;
          ??? retrun v_result;
          ? exception
          ??? when zero_divide then
          ?????? raise_application_error(-20000,'zero divied');
          ? end;
          ?5) 函數調用的限制
          ? -- 在sql 語句中只能調用存儲函數
          ? -- 在sql 語句中只能調用帶有輸入參數in ,而不能有輸出參數out 和in out 參數的函數
          ? -- 在sql 語句中調用的函數的參數必須是標準的sql 數據類型,不能是pl/sql 所特有的數據類型
          ? -- 在sql 語句中調用的函數不能包含insert,update 和delete
          ?6) 查看源代碼
          ? set pagesize 40
          ? select text form user_source where name='result';
          ?7) 刪除函數
          ? drop function result;
          ?3 管理子程序
          ? 1) 列出當前用戶的子程序
          ?? select object_name,created,status form user_objects
          ?? where object_type in ('procedure','function');
          ? 2)列出子程序源代碼
          ?? select text from user_sorce where name='raise_salary'
          ? 3)類出子程序編譯錯誤
          ??? -- show errors
          ??? --使用數據字典user_errors? 確定錯誤原因和位置
          ???? select line||'/'||position as "line/col",text error
          ???? from user_errors where name='raise_salary';
          ?? 4) 列出對象的依賴關系
          ??? -- 使用 user_dependenciess 確定直接依賴關系
          ??? select name,type from user_dependencies
          ??? where referenced_name='emp'
          ??? -- 使用 deptree 和 ideptree 確定依賴和見解依賴關系
          ??? select nested_level,name,type from deptree;
          ?? 5) 重新編譯子程序
          ???? 當被應用對象的結構被修改以后,就會將相關依賴對象轉變為無效invalid ,需要重新編譯
          ???? 1
          ???? alter table emp add remark varchar2(100);
          ???? 2
          ???? select object_name,object_type from user_objects
          ???? where status='invalid'
          ???? 3
          ???? alter procedure add_employee compile;
          ???? alter view dept10 compile;
          ???? alter function get_info compile;
          ?????
          ??

          posted @ 2006-10-11 14:51 康文 閱讀(293) | 評論 (0)編輯 收藏

          處理例外

          1例外簡介
          ?1) 例外分類
          ? 預定義分類,非預定義分類,自定義例外。
          2 處理預定義例外
          ? 1) 常用預定義例外
          ?? a access_into_null;
          ???? create type emp_type as object
          ???? (name varchar2(2),sal number(6,2));
          ????
          ???? declare
          ?????? emp emp_type;
          ???? begin
          ?????? emp.name:='scott';
          ???? exception
          ?????? when access_into_null then
          ????????? dbms_output.put_line('首先初始化對象emp');
          ??? b case_not_found
          ???? undef no
          ???? declare
          ?????? v_val emp.sal%type;
          ???? begin
          ?????? select sal into v_sal from emp where empno=&no;
          ?????? case
          ???????? when v_sal<1000 then
          ?????????? update emp set sal=sal+100 where empno=&no;
          ???????? when v_sal<2000 then
          ?????????? update emp set sal=sal+150 where empno=&no;
          ???????? when v_sal<3000 then
          ????????? update emp set sal=sal+200 where empno=&no;
          ?????? end case;
          ?????? exception
          ???????? when case_not_found then
          ?????????? dbms_output.put_line();
          ????? end;
          ??? c collection is null
          ??? 在給集合元素(嵌套表或array類型)賦值前,必須首先初始化集合元素
          ??? declare type ename_table_type is table of emp.eanme%type;
          ??? ename_table ename_table_type;
          ??? begin
          ????? select e_name into ename_talbe(2) from emp where empno=$no;
          ??? exception
          ????? when collection_is_null then
          ??????? dbms_output.put_lilne('必須使用構造方法初始化集合元素');
          ??? end;
          ??? d currsor_already_open
          ??? reopen curosr 如果用戶已經使用了open 命令打開了顯示游標,或執行for循環(隱式的打開游標)
          ?????? delcare
          ???????? cursor emp_surosr is select ename,sal,from emp;
          ?????? begin
          ???????? open emp_curosr;
          ???????? for emp_record in emp_cursor loop
          ????????????? dbms_output.put_line(emp_record.eanme);
          ???????? end loop;
          ?????? exception
          ????????? when cursor_already_open then
          ??????????? dbms_output.put_line("游標已經打開");
          ?????? end;
          ???? e dup_val_on_index
          ???? begin
          ???? exception
          ??????? when dup_val_on_index then
          ??????? dbms_output.put_line("列上不能出現重復值");
          ???? end;
          ???? d invalid_curosr
          ???? delcare
          ?????? curosr emp_cursor is select ename,sla from emp;
          ?????? emp_record emp_crusor%rowtype;
          ???? begin
          ?????? fetch emp_cursor into emp_record;
          ?????? close emp_crusro;
          ???? exception
          ?????? dbms_output.put_line("游標沒有打開");
          ???? end;
          ???? f invalid_number? can not convert char to nmuber successfully
          ?????? begin
          ???????? update mep set sal=sal+1oo;
          ?????? exception
          ???????? when invalid_number then
          ???? g no_data_found? when select into is executed ,no row is returned?????
          ?????? declare
          ???????? v_sal emp.sal%type;
          ?????? begin
          ????????? select sal into v_cal form emp where lower(ename)=lower('&name');
          ?????? exception
          ???????? when no_data_found then
          ???????????? dbms_output.put_line('沒有返回結果');
          ?????? end;
          ????? h too_many_row? ora -01422 there are too many are return when "select into" is executed
          ????? i zero_divide ora-01476
          ????? g subscript_beyond_count ora-065533
          ????? declare
          ??????? type emp_array_type is varray(20) of varchar2(10);
          ??????? emp_array emp_array_type;
          ????? begin
          ???????? emp_array:=emp_array_type('scott','mary');
          ???????? dbms_output.put_line('emp_array(3)');
          ????? exception
          ???????? when subscript_beyone_count then
          ????????? dbms_out.put_line('超出下標范圍');
          ????? end;
          ????? k subscript_outside_limit
          ?????? emp_array(-1);
          ????? l value_error the length of variable cannot contain the actual value;
          ????? declare
          ????? begin
          ????? end;
          3 處理非預定義例外
          ? delcare
          ??? e_integrity exception;
          ??? pragma exception_init(e_integrity,-2291);
          ? begin
          ??? update emp set deptno=dno where empno=&no;
          ? exception
          ??? when a_integrity then
          ? end;
          4 處理自定義例外
          ? 與oracle 錯誤沒有任何聯系,為業務邏輯所定義的例外
          ? delcare
          ??? e_no_employee exception;
          ? begin
          ??? update emp set deptno=&dno where empno=&eno;
          ? if sql%notfound then
          ??? raise e_no_employee;
          ? end if;
          ? exception
          ??? when e_no_emplyee then
          ???? dbms_output.put_line('該雇員不存在');
          5 使用錯誤例外函數
          ? 使用例外函數可以取得錯誤號以及相關的錯誤消息,sqlcode 用于取得oracle 的錯誤號,而sqlerrm
          則用于取得與之相關的錯誤信息。
          ? 1 sqlcode 和 sqlerrm
          ? 為了在pl/sql 應用程序中處理其他為預料的到的oracle 錯誤,用戶可以在例外處理部分的
          when others 自句后,引用兩個函數
          ? declare
          ??? v_ename emp.ename%type;
          ? begin
          ??? select ename into v_ename form emp where sal='&v_sal';
          ? exception
          ??? when no_data_found then
          ??? when others then
          ?????? dbms_output.put_line(sqlcode);
          ?????? dbms_output.put_line(sqlerrm);
          ? end;
          ? 2 raise_aaplicaition_error
          ?? 只能在子程序中使用(過程,函數,包,觸發器)
          ?? raise_application_error(error_number,message,[true|false]);
          ?? error_number 錯誤號,在-20000到-20999 之間
          ?? message 指定錯誤消息,不能超過2048?
          ?? if v_comm is null then
          ?????? raise_application_error(-20001,'該雇員無補助');
          ?? end if;

          posted @ 2006-10-11 14:46 康文 閱讀(301) | 評論 (0)編輯 收藏

          開發包

          1建立包
          ?1) 建立包規范: 用于定義包的公共組建,包括常量,變量,游標,過程和函數等
          ?create or replace package emp_package is
          ? g_deptno number(3):=30;
          ? procedure add_employee(eno number,name varchar2,salary number dno number default g_deptno);
          ? procedure fire_empoyee(eno number);
          ? function get_sal(eno number) return number;
          ?end emp_package;
          ? 2) 建立包體
          ?? 用于實現包規范所定義的過程和函數。在包體中也可以單獨定義私有組件,包括變量,常量,過程和函數等。但在包體中所定義的組件只能在包內使用,而不能由其他子程序引用。
          ?? create or replace package body emp_package is
          ??? function validate_deptno(v_deptno number)
          ????? return boolean;
          ??? is
          ????? v_temp int;
          ??? begin
          ????? select 1 into v_temp from dept where deptno=v_deptno;
          ????? return true;
          ??? exception
          ????? when no_data_found then
          ?????? return false;
          ??? end;
          ??? procedure add_employee(eno number,name varchar2,salary number,dno number default g_deptno)
          ??? is
          ??? begin
          ????? if validate_deptno(dno) then
          ??????? insert into emp(empno,ename,sal,deptno)
          ???????? values(eno,name,salary,dno);
          ????? esle
          ??????? raise_application_error(-20011,'部門不存在');
          ????? end if;
          ??? exception
          ????? when dup_val_on_index then
          ??????? raise_application_error(-20011,'該雇員已存在')
          ??? end;
          ??? procedure fire_employee(eno number) is
          ??? begin
          ????? select from emp where empno=eno;
          ????? if sql%notfound then
          ???????? raise application_error(-20012,'');
          ????? end if;
          ??? end;
          ?? function get_sal(eno number) return number
          ?? is
          ???? v_sal emp.sal%type;
          ?? begin
          ???? select sal into v_sal from emp where empno=eno;
          ???? return v_sal;
          ?? exception
          ???? when no_data_found then
          ?????? raise_application_error(-200012,'');
          ?? end;
          ? end emp_package;
          ? 3) 調用包組建
          ??? -- 在同一個包內調用組建 不需要加包名前綴,直接調用
          ? create or replace paclage body emp_package is
          ??? procedure add_employee(eno number,name varchar2,salary number,dno number default g_deptno)
          ??? is
          ??? begin
          ????? validate_deptno(dno) then
          ??? exception
          ??? end;
          ?? -- 調用包公用變量
          ?? exec emp_package.g_deptno:=20
          ?? -- 調用公用過程
          ?? exec emp_package.add_employee(111,'mary,2000');
          ?? -- 調用遠程數據庫包的公用組件
          ?? exec emp_paclage.add_employee@orasrv(1116,'scott',1200);
          ?? 4) 查看包源代碼
          ?? select text from user_source where name='emp_package' and type='package';
          ?? 5) 刪除包
          ?? drop packagee emp_package;
          2 使用包重載
          ? 指多個具有相同名字的子程序,在調用的時候使用不同的參數傳遞。
          ? 1) 建立包規范
          ?? 同名過程和函數必須具有不同的輸入參數,但同名函數返回值的類型數據必須相同
          ??? create or replace package overload is
          ??? function get_sal(eno number) return number;
          ??? function get_sal(name varchar2) return number;
          ??? procedure fire_employee(eno number);
          ??? procedure fire_employee(name varchar2);
          ?? 2) 建立包體
          ??? 。。。
          3) 使用包構造過程
          ?初始化全局變量
          ?1 建立包規范
          ?? create or replace packiage emp_package
          ?? is
          ?? minsal number(6,2);
          ?? maxsal number(6,2);
          ?? procedure upd_sal(eno number,salary number);
          ?? procedure upd_sal(name varhcar2,salary number);
          ?? end;-- 定義了兩全局變量和三個公用過程
          ?? 2 建立包體
          ??? create or replace package body emp_package is
          ????? procedure add_employee(cno number,name varchar2,salary number,dno number)
          ????? is
          ????? begin
          ??????? if salary between minsal and maxsal then
          ????????? insert into emp(empno,ename,sal,deptno)
          ???????? ........
          ??? -- 構造過程,位于子程序尾部,已begin 開始已end 結束
          ???? begin
          ?????? select min(sal),max(sal) into minsal,maxsal from emp;
          ???? end;
          ????? end;
          3 調用包公用組建
          ?? 在同一次會話中第一次調用包的公用組建時,會自動執行其它構造函數,而將來調用其他組建時則不會再調用其構造過程。
          4 使用純度級別
          ?1 家里包規范
          ? create or replcace package purity is
          ? minsal number(6,2);
          ? maxsal number(6,2);
          ? function max_sal return number;
          ? function min_sal return number;
          ? pragma restrict_references(max_sal,wnps);--wnps 不能修改包的變量(不能給包的變量賦值)??????????????????????????????????????????? --wnds 不能執行dml
          ? pragma restrict_references(min_sal,wnps);--rnps 用于限制函數不能讀取包變量
          ? end;

          posted @ 2006-10-11 14:46 康文 閱讀(362) | 評論 (0)編輯 收藏

          including Constraints

          1 What are Constrains
          ? 1) Constrains enforce on the table level
          ? 2) Constrains the deletion of a table if there are dependencies
          2 Constrain Guidelines
          ? 1) Name a constraint or the oracle generate a name by the sys_cn format
          ? 2) Create a constraint either
          ???? --At the same time as the table is created.or
          ???? --After the table has been created
          ? 3)Define a constraint at the column or table level
          ? 4)view constraint in the data dictionary
          3 Crete a constraint
          ? create table test2
          ? (id int not null,-- column level
          ?? lname varchar(20),
          ?? fname varchar(20),
          ?? constraint uk_test2_1 unique(lname,fname))--table level
          4 The not null Constraint
          ? create table employees(
          ?? employee_id number(6),
          ?? last_name?? varchar2(25) not null? --system named
          ?? hire_date?? DATE
          ?????????????? constraint emp_hire_date not null --User named
          5Foreign key
          ? create table test3
          ? (rid int,
          ?? name varchar(30),
          ?? constraint fk_test3_1 foreign key(rid) reference test2(id));
          ? froeign key constraint keywords
          ??? foreign key :Define the column in thee child table at the table constrain level.
          ??? references? :Identifies the table and column in the parent table.
          ??? on delete cascade: Delete the dependent rows in the child table when a row in the???? parent table is deleted
          ??? on delete set null:Convert the dependent foreign key values to null when a row in the
          ??? parent table is deleted.
          ??
          ??? --parent table referenced table
          ??? --child table refernce other table
          6 The check Constraint
          ? Define a condition that each row must be satisfy
          ? alter table test3
          ? add constrain ch_test3 check(name like 's%')
          7 Dropping a Constraint
          ? 1) Remove the manager constraint form the employee table
          ?? alter table test3
          ?? drop constriant test3_manager_fk
          ? 2) Remove the primary key constraint on the departments table and drop the associated
          ?? foreign key constraint on the employees.department_id column
          ?? alter table departments
          ?? drop primary key cascade
          8 Disabling and enable Constraints
          ? 1)Execute the disable clause of the alter table statment to deactive an integrity constraint
          ? 2)Apply the cascade option to disable dependent integrity constrints
          ? alter table employees
          ? disable constraint emp_emp_id_pl cascade
          ? 3) enabling Constraints
          ? .Active an integrity constraint currently disabled in the table definition by using the enable clause.
          ?? alter table employees
          ?? enable constraint emp_emp_id_pk;
          ? a unique? or a primary? index is automatically created if you enable a unique key or a primary key constraint?
          ?8 View Constraints
          ? select constraint_name,constriant_type,serch_condition
          ? from user_constraints
          ? where table_name='employees'
          ?9 view the columns associated with constraints
          ?select constraint_name,column_name
          ?from user_cons_columns
          ?where table_name='employees'

          posted @ 2006-10-11 14:45 康文 閱讀(239) | 評論 (0)編輯 收藏

          create view

          1Why Use Views
          ? to restrict data access
          ? to make complex query easy
          ? to provide data independence
          ? to provide defferent view of the same data
          2 Creating a View
          ? 1)create [or replace] [force|noforce] view view
          ? as subquery
          ? force : create view wether the referenced object existed or not
          ?
          ? desc view_name;
          ?2)create a view by using column aliases in the subquery
          ? create view salv50
          ? as select employee_idIO_NUMBER,last_name NAME,slaary*12 ANN_SALARY
          ? from employees
          ? where department_id=50;
          3 Modigy a View
          ? 1) Modigy the emplvu80 view by using create or replace view clause.Add an alias for each column name;
          ?? create or replace view empvu80
          ?? (id_number,name,sal,department_id)
          ?? as select employee_id,first_name||" "||last_name,salary.department_id
          ?? from employees
          ?? where department_id=80;
          ?? column aliases in the create view clause are listed in the same order as the columns in the subquery
          ?? note : alter view_name is not a valid command.
          4 Create a Complex View
          ? Create a complex view that contains group functions to display values from two tables
          ? create view dept_sum_vu
          ?? (name,minsal,maxsal,avgsal)
          ? as
          ?? select d.department_name,min(e.salary),max(e.salary),avg(e.salary)
          ?? from employees e,departments d
          ?? where e.department_id=d.department_id
          ?? group by d.department_name;
          5 Rules for performs DML operaton on a view
          ? 1) You can perform DML operation on simple views
          ? 2) You can not romove a row if the view contains the following:
          ??? --group functions
          ??? --a group by clause
          ??? --the distinct keyword
          ??? -- rownum keyword
          ??? -- column defined by expressions
          6 Using the with check option Clause
          ? 1) you can ensure that dml operatons performed on the view stay within the domain of the view by using the with check option clause.
          ? create view test1
          ? as
          ? select * from emp where qty>10;
          ? with check option;
          ? update testview1 set qty=10
          ? where ster_id=6830;
          ? --when you doing the following update operation
          ? update testview1 set qty=5 where id=10;
          ? -- an error will report
          ? --you violate the where clause
          ? 2)Any attempt to change the department number for any row in the view fails because it violates the with check option constraint
          ?? create or replace view empvu20
          ?? as
          ?? select * where department_id=20
          ?? with check option constriant empvu20_ck;
          7 Denying DML Operations
          ? 1 You can ensure that no dml operations occur by adding the with read only option to your view definition.
          ? 2)Any attempt to a DML on any row in the view resuls in an oralce server error.
          8 remove veiw
          ? drop view_name
          9 inline view
          ? 1) an inline view is a subquery with an alias that you can use within a sql statement.
          ? 2) a named subquery in the from clause of the main query is an exqmple of an inline view
          ? 3) an inline view is not a schema object.
          10 Top-N Analysis
          ?1)Top_N querise ask for the n largest or smallest values of a column.
          ?2)Both largest values and smallest values sets considered Top-N queries
          ? select * from (select ster_id,qty from sales);
          ?example
          ? To display the top three earner names and salaries from the employees
          ? select rownum as rank,last_name,salary
          ? from (select last_anme,slary from employee
          ??????? order by slary desc)
          ? where rownum<=3;
          ?

          posted @ 2006-10-11 14:45 康文 閱讀(303) | 評論 (0)編輯 收藏

          使用觸發器

          1 觸發器簡介
          ? 1) 觸發事件
          ? 2) 觸發條件
          ? 3) 觸發操作
          ???? . 觸發器代碼的大小不能超過32k,如果使用大量代碼建立觸發器,應該先建立存儲過程,然后再觸發器中使用call語句調用存儲過程。
          ???? . 觸發器中正能含有select ,insert,update 和delete 語句,而不能含有ddl 語句,和事物控制語句。
          2 建立dml 觸發器
          ?1) 觸發時機
          ? before,after 表示在執行dml操作之后觸發器
          ?2)觸發事件
          ? insert ,update 和delete 操作。也可以使用書法事件
          ?3) dml 觸發器是針對特定表進行的 因此必須制定dml 操作所對應的表
          ?4) 觸發器類型 用于指定當觸發器事件之后,需要執行幾次觸發器操作。如果指定語句觸發器類型
          那么會執行一次觸發器代碼:如果指定行觸發器類型,則會在每個被作用行上執行一次觸發器代碼。
          ?5) 觸發條件
          ?用于指定執行行觸發器代碼的條件,只有為ture時,才會執行行觸發器代碼。
          ? 6) 如果使用pl/sql 存儲過程,java 存儲過程,或外部處處過程需要在觸發器操作部分直接使用call
          ? 7) dml 觸發器觸發順序
          ?? (1)dml 觸發器在單行數據上的觸發順序。
          ??? 對于單行數據而言,無論是語句此觸發器,還是行觸發器,觸發器代碼實際只執行一次,并且執行
          順序為before 語句觸發器,before 行觸發器,dml 操作,after 行觸發器,after 語句觸發器
          ?? (2) dml 觸發器在多行數據上的觸發順序
          ??? before 語句觸發器
          ??? before 行觸發器
          ??? after 行觸發器
          ??? before行觸發器
          ??? after 行觸發器
          ??? after語句觸發器
          ?? 語句觸發器只被執行一次,而行觸發器在每個行上都執行一次。
          ? 2) 語句觸發器
          ? 當審計dml 操作,或確保dml操作安全執行時,可以使用語句觸發器
          ? 1 建立before 語句觸發器
          ?? create or replace trigger tr_sec_emp
          ?? before insert or update or delete on emp
          ?? begin
          ???? if to_char(sysdate,'DY','nls_dtate_language=AMERICAN') in ('sat','sun') then
          ???? railse_application_error(-200001,'不能在休息日改變雇員信息');
          ???? end if;
          ?? end;?
          ?? 2 使用條件謂詞
          ?? inserting ,updating ,deleting
          ?? create or replace trigger tr_sec_emp
          ?? before insert or update or delete on emp
          ?? begin
          ???? if to_char(sysdate,'DY','nls_date_language=american')
          ????? in('sat','sun') then
          ???? case
          ?????? when inserting then
          ???????? raise_application('-20001','inserting');
          ?????? when updating then
          ???????? raise_application('-20002','updating');
          ?????? when deleting then
          ???????? raise_application('-20003','deleting');
          ???? end case;
          ??? end if;
          ?? end;
          ?? 3 建立after 語句觸發器
          ??? 為了dml 操作,或者dml 操作后執行匯總運算
          ?? create table aduit_table(
          ???? name varchar2(20),ins int,upd int,del int,
          ???? starttime date,endtime date
          ?? );
          ?? create or replace trigger tr_aduit_emp
          ?? after insert or update or delete emp
          ?? declare
          ???? v_temp int;
          ?? begin
          ???? select count(*) into v_temp from aduit_table
          ?????? where name='emp';
          ???? if v_temp=0 then
          ?????? insert into audit_table values
          ?????? ('emp',0,0,0,sysdate,null);
          ???? end if;
          ???? case
          ?????? when? inserting then
          ???????? update aduit_table set ins=ins+1,endtime=sysdate where name='emp';
          ?????? when updating then
          ???????? update audit_table set upd=upd+1,endtime=sysdate where name='emp';
          ?????? when deleting then
          ???????? update aduit_table set del=del+1,endtime=sysdate where name='emp';
          ?? end;
          ? 3) 行觸發器
          ?? 審計數據變化可以使用行觸發器
          ?? 1 建立不before 行觸發器
          ??? 為了取保數據符合商業邏輯或企業規則,對輸入的數據進行復雜的約束,可以使用before行觸發器
          ???? create or replace trigger tr_emp_sal
          ???? before update of sal on emp
          ???? for each row
          ???? begin
          ?????? if :new.sal<:old.sla then
          ???????? raisse_application_error(-200010,'工資只漲不降');
          ?????? end if;
          ???? end;
          ???? 2) 建立after 行觸發器
          ???? 為了審計dml 操作,可以使用語句觸發器或oracle 系統提供的審計功能,而為了審計數據變化
          ,則應該使用after 行觸發器
          ???? create table audit_emp_change(
          ?????? name varchar2(10),odl number(6,2),
          ?????? newsal number(6,2),time date);
          ??? create or replace trigger tr_sal_change
          ??? after update of sal on emp
          ??? for each row
          ??? declare
          ???? v_temp int;
          ??? begin
          ???? select count(*) into v_temp from audit_emp_change where name=:old.ename;
          ??? if v_temp =0 then
          ????? insert into audit_emp_change
          ??????? values(:old,ename,:old.sal,:new,sal,sysdate);
          ??? else
          ????? update audit_emp_change
          ??????? set oldsal=:old.sal,newsal=:new.sal,time=sysdate where name=:old.ename;?
          ??? end if;

          ??? end;
          ???? )
          ??? 3) 限制行觸發器
          ??? 當使用行觸發器,默認情況下會咱每個被作用行上七星一次觸發器代碼,為了時得再特定條件下執行行觸發器代碼,需要使用when 子句
          ??? create or replace trigger tr_sal_change
          ??? after update of sal on emp
          ??? for each row
          ??? when(old.job='salesman')
          ??? declare
          ?????? v_temp int..
          2 dml 觸發器使用注意事項
          ? 觸發器代碼不能從觸發器所對應的基表中讀取數據
          3 dml 觸發器
          ? 為了保證數據庫滿足特定的商業規則或企業邏輯,可以使用約束,觸發器和子程序。約束性能最好,實現最簡單,所以為售選,如果觸發器不盟實現,可以選擇觸發器。
          ? dml 觸發器可以用于實現數據安全保護,數據審計,數據完整性,參照完整性,數據復制等功能。
          ?1) 控制數據安全
          ? create or replace trigger tr_emp_time
          ? before insert or update or delete on emp
          ? begin
          ??? if to_char(sysdate,'hh24') not between '9' and '17' then
          ????? raise_application_error(-20101,'not work time');
          ???? end if;
          ? end;
          ? 2) 實現數據審計
          ? 使用數據審計只能審計sql 操作,而不會記載數據變化
          ? audit insert,update,delete on emp by access
          ? 3)實現數據完整性
          ? 首選約束 alter table emp add constraint ck_sal check (sal>=800),但是在有些情況下只能使用觸發器來實現數據完整性
          ?? create or replace trigger tr_check sal
          ?? before update of sal on emp
          ?? for each row
          ?? when (new.sla<old.sal or new.sal>1.2* old.sal)
          ?? begin
          ????? raise_application_error(,,,,,,)
          ?? end;
          ? 3) 使用引用完整性
          ? 采用 on delete cascade 可以進行集聯刪除,但是卻不能進行集聯更新。采用觸發器實現集聯更新
          ?? create or replace trigger tr_update
          ?? after update of sal on emp
          ?? for each row
          ?? begin
          ???? update emp set depno=:new.deptno where dentno=:old.deptno;
          ?? end;
          4 建立instead of 觸發器
          ? 對于簡單視圖可以直接進行insert update 和delete 等操作,但是對于復雜視圖不允許進行insert,update 和delete 操作。
          ? 滿足一下條件的為復雜視圖
          ??? 具有操作集合符 union,union all ,intersect,minus
          ??? 具有分組函數 min,max,avg,sum,count
          ??? 具有group by connect 編譯 或start with
          ??? 具有distinct
          ??? 具有連接
          ? 為了在復雜視圖上執行dml 操作,必須要基于instead-of 觸發器,建立instead-of 觸發器后,就可以基于復雜視圖執行insert,update和delete 語句。
          ?? instead of 選項只使用于視圖
          ?? 基于視圖建立觸發器時,不能定義before 和 after
          ?? 在建立視圖時不能指定 with check option
          ?? 當建立instead of 觸發器時,必須指定for each row 選項
          ? 1) 建立復雜視圖dept_emp
          ?? create or replace view dept_emp as
          ?? select a.deptno,a.dname,b,empno,b,ename
          ?? from dept a,emp b
          ?? where a,deptno=b.deptno;
          ? 2) 建立 instead-of 觸發器
          ?? create of replacee trigger tr_instead_of_dept_emp
          ?? instead of insert on dept_emp
          ?? for each row
          ?? declare
          ???? v_temp int;
          ?? beegin
          ????? select count(*) into v_temp from dept where deptno=:new.deptno;
          ????? if v_temp=0 then
          ??????? insert into dept(deptno,dname) values(:new.deptno,:new.dname);
          ????? end if;
          ????? select count(*)into v_temp from emp where empno=:new.empno;
          ????? if v_temp=0 then
          ???????? insert into emp(empno,ename,deptno)
          ?????????? values(:new.deptno,:new.ename,:new.deptno);
          ???????? end if;
          ?? end;
          ??
          ?? 可以對視圖執行insert 操作了
          ??? insert into dept_emp values(50,'admin','1223','mary')
          5 管理觸發器
          ? 1) 顯示觸發器信息
          ??? select trigger_name,status from user_triggers
          ??? where table_name='emp';
          ?? 2)禁止觸發器
          ??? alter trigger tr_check_sal disable;
          ?? 3) 激活觸發器
          ??? alter trigger tr_check_sal enable;
          ?? 4) 禁止或激活表上的所有觸發器
          ??? alter table emp disable all triggers;
          ??? alter table emo eanble all triggers;?
          ?? 5)重新編譯觸發器
          ??? alter trigger tr_check_sal compile;
          ?? 6) 刪除觸發器
          ??? drop trigger tr_check_sal;

          posted @ 2006-10-11 14:44 康文 閱讀(1022) | 評論 (0)編輯 收藏

          使用復合變量

          1 pl/sql 集合 處理單列多行數據庫,使用的類型為標量類型
          ?1)索引表
          ? type ename_table_type is table of emp.ename%type
          ??? index by binary_integer;
          ? ename_table ename_table_type;
          ? begin
          ??? select ename into ename_table(-1) from emp
          ????? where empno=&no;
          ??? dbms_output.put_line('雇員名:'||ename_table(-1));
          ? end;
          ?
          ?? set serveroutput no
          ?? declare
          ???? type area_table_type is table of number
          ??????? index by varchar2(10);
          ???? rea_table area_table_type;
          ??? begin
          ??????? area_table('beijing'):=1;
          ??????? area_table('shanghai'):=2;
          ??????? area_table('guangzhou'):=3;
          ??????? dbms_output.put_line(area_table.first);
          ??????? dbms_output.put_line(area_table.last);
          ??? end;
          ???? 2) 嵌套表
          ????? 索引表類型不能作為累得數據類型使用,但是嵌套表可以作為表類的數據類型使用。
          當使用嵌套表元素時,必須先用其構造方法初始化其嵌套表:
          ?????? a? 在pl/sql 塊中使用嵌套表
          ??????? declare
          ????????? type ename_table_type is table of emp.ename%type;
          ????????? ename_table ename_table_type;
          ??????? begin
          ?????????? ename_table:=eanme_table_type('2','2','3');
          ?????????? select ename into ename table(2) from emp where empno=&no;
          ?????????? dbms_ouput.put_line(ename_table(2));
          ??????? end;
          ????? b 在表中使用嵌套表
          ??????? create type phone_type is table of varchar2(20);
          ??????? create table employee(
          ????????? id number (4),name varchar2(10),sal number(6,2),
          ????????? phone phone_type
          ??????? )nested table phone store as phone_table;
          ?????? -- 為嵌套表插入數據
          ??????? insert into employee values(2,'scott',200,phone_type('2222','333333'));
          ?????? --檢索嵌套表累得數據
          ??????? set serveroutput on
          ??????? declare
          ????????? phone_table phone_type;
          ??????? begin
          ????????? select phone into phone_table
          ????????? from employee where id=1;
          ????????? for i in 1..phone_table.count loop
          ??????????? dbms_output.put_line(phone_table(i));
          ????????? end loop;
          ??????? end;
          ?????? -- 更新嵌套表列的數據
          ???????? delcare
          ??????????? phone_table phone_type:=('44444','555555');
          ???????? begin
          ??????????? update employee set phone=phone_table
          ??????????? where id=1;
          ???????? end;
          ??? 3) 變長數組
          ????? 在使用varray 時必須指定最大個數,和數據類型,在使用其元素時必須進行初始化
          ????? type ename_table_type is varray(20) of emp.ename%type;
          ????? ename_table ename_table_type:=ename_table_type('1','2');
          ?????
          ????? -- 在快中使用varray
          ????? declare
          ???????? type ename_table_type is varray(20) of emp.ename%type;
          ???????? ename_table ename_table_type:=ename_table_type('mary');
          ???????? begin
          ??????????? select ename into ename_table(1) form emp
          ?????????????? where empno=&no;
          ????????? end;
          ????? --在表列中使用varray
          ?????? create type phone type is varray(20) of varchar2(20);
          ?????? create table employee(
          ???????? id number(4),name varchar2(10),
          ???????? sal number(6,2),phone phone_type);
          ??????
          ???? 3)記錄表
          ????? 記錄表結合了記錄和集合的優點
          ??????? declare
          ????????? type emp_table_type is table of emp%rowtype
          ????????? index by binary_integer;
          ??????? emp_table emp_table_type;
          ??????? begin
          ????????? select * from into emp_table(1) from emp
          ????????? where empno=&no;
          ????????? dbms_output.put_line(emp_table(1).ename);
          ??????? end;
          ????? 4)多維集合
          ?????? 1 多級varray
          ?????? declare
          ??????? --define 一維集合
          ????????? type al_array_type is varray(10) of int;
          ??????? --定義二維集合
          ????????? type nal_varray_type is varray(10) of a1_varray_type;
          ??????? --初始化二維集合
          ????????? nvl nal_varray_type:=nal_varray_type(
          ??????? ???? a1_varray_type(1,2),
          ??????????? a1_varray_type(2,3)
          ????????? )
          ???????? beign
          ?????????? for i in 1..nal_varray_type.count loop
          ????????????? for j in 1..a1_array_type.count loop
          ??????????????? dbms_out.putline(nvl(i)(j));
          ????????????? end loop;
          ?????????? end loop;
          ??????? end;
          ?????? 2 使用多級嵌套表
          ??????? table a1_table_type is table of int;
          ??????? table nvl_table_type is table of a1_table_type;
          ??????? nvl nvl_table_type:=nvl_table_type(
          ????????? a1_table_type(1,2),
          ????????? a1_table_type(2,3)
          ??????? );
          2 集合方法
          ? 1) exist
          ?? if ename_table.exists(1) then
          ??? ename_table(1):='scott';
          ?? 2) count 返回當前集合變量中的元素總個數
          ??? ename_table.count
          ?? 3) limit 返回集合元素的最大個數? 只有varray 有
          ?? 4)first and last
          ?????? ename_table.first
          ?????? ename_table.last
          ?? 5) prior 和next
          ??? ename_table.prior(5); --返回元素5的前一個
          ??? ename_table.next(5);? --? 后一個
          ?? 6) extend
          ??? 使用于varray 和 嵌套表。
          ??? extend add a null value
          ??? extend (n) add n null value
          ??? extend (n,i)add n i value
          ??? declare
          ????? type ename_table_type is varray(20) of varchar2(20);
          ????? ename_table ename_table_type;
          ??? begin
          ????? ename_table:=ename_table_type('mary');
          ????? ename_table.extend(5,1);
          ????? dbms_output.put_line(ename_table.count);
          ??? end;
          ?? 7) trim
          ?? trim remove one element from the tail of the collection.
          ?? trim(n) remove n element from the tail of the colleciton.
          ?? 8)delete
          ??? delete: delete all the elements
          ??? delete(n) :delete the nth elements
          ??? delete(m,n): delete the elements from m to n
          3 集合賦值
          ? 1)將一個集合的數據賦值給另一個集合.clear the destination collectins and set the original collection
          ?? delcare
          ??? type name_varray_type is varray(4) of varchar2(10);
          ??? name_array1 name_varray_type;
          ??? name_array2 name_varray_type;
          ?? begin
          ???? name_array1:=name_varray_type('scott','smith');
          ???? name_array2:=name_array_type('a','b','c');
          ???? name_array1:=name_array2;??
          ?? end;
          ??
          ?
          ? type name_array1_type is varray(4) of varchar2(10);
          ? type name_array2_type is varray(4) of varchar2(10);
          ? name_array1 name_array1_type;
          ? name_array2 name_array2_type;
          ? 具有相同的數據類型,單具有不同的集合類型不能構賦值
          ? 2) 給集合賦城null 值
          ??? 可以使用delete 或 trim
          ??? 也可以使用 空集合賦給目表集合
          ??? type name_varray_type is varray(4) of varchar2(10);
          ??? name_array name_varray_type;
          ??? name_empty name_varray_type;
          ???
          ??? name_array:=name_varray_type('1','2');
          ??? name_array:=name_empty;
          ? 3) 使用集合操作賦和比較集合都是10g 的內容,p176 先略過。
          4 批量綁定
          ? 執行單詞sql 操作能傳遞所有集合元素的數據。
          ? 1 forall 語句
          ? 用于insert update 和delete操作。在oracle9i 中forall 語句必須具有連續的元素
          ??? 1) using forall on insert
          ???? declare
          ??????? type id_table_type is table of number(6)
          ??????? index by binary_integer;
          ??????? type name_table_type is table of varchar2(2)
          ??????? index by binary integer;
          ??????? id_table id_table_type;
          ??????? name_table name_table_type;
          ????? begin
          ???????? for i in 1..10 loop
          ?????????? id_table(i):=i;
          ?????????? name_table(i):='Name'||to_char(i);
          ???????? end loop;
          ???????? forall i in 1..id_table.count
          ?????????? insert into demo values(id_table(i),name_table(i));
          ????? end;
          ???? 2)using forall on using update
          ?????? forall i in 1..id_table.count
          ?????????? upate demo set name:=name_table(i)
          ????????????? where id:=id_table(i);
          ???? 3)using forall on using delete
          ??????? forall i in 1..id_table.count
          ??????????? delete from demo where id:=id_table(i);
          ???? 4) using forall on part of the collection
          ??????? for i in1..10 loop
          ????????? id_table(i):=i;
          ????????? name_table(i):="name"||to_char(i);
          ??????? end loop;
          ??????? forall i in 8..10 l
          ?????????? insert into demo values(id_table(i),name_table(i));
          ?? 2 bulk collect
          ???? is fit for select into ,fetch into and dml clause
          ???? 1) using bulk collect
          ????? declares??
          ??????? type emp_table_type is table of emp%rowtype
          ???????? index by binary_integer;
          ??????? emp_table emp_table_type;
          ????? begin
          ???????? select * bulk collect into emp_table
          ????????? from emp where deptno=&no;
          ???????? for i in 1..emp_tablee.count loop
          ??????????? dbms_output.put_line(emp_table(i).ename);
          ???????? end loop;
          ????? 2) 在dml 的返回字句使用bulk collect 字句
          ???????? declare
          ????????? type ename_table_type is table of emp.ename%type;
          ?????????? ename_table ename_table_type;
          ????????? begin
          ???????????? deletee from emp where deptno=&no
          ???????????? returning ename bulk_collect into ename_table;
          ????????? for i in 1..ename_table.count loop
          ??????????? dbms_output.put(ename_table(i));
          ????????? end loop;
          ??????? end;
          ????????? end;
          ????? end;

          posted @ 2006-10-11 14:44 康文 閱讀(344) | 評論 (0)編輯 收藏

          advanced subquery

          1 subquery: is a select statement embedded in other sql statement.
          ? .the subquery execute (inner query) once before the main query
          ? .the result of the subquery is used by the main query.
          2 pairwise comarison subquery
          ?select * from employee
          ?where (manager_id,department_id) in
          ????????? (select manager_id,department_id
          ?????????? from employees
          ?????????? where employee_id in (178,174))
          ?and employee_id not in (178,174);
          ?nonpairwise comparison subquery
          ?select employee_id,manager_id,department_id
          ?from employee
          ?where manager_id in
          ????????????????? (select manager_id
          ?????????????????? from employees
          ?????????????????? where employee id in (174,141))
          ?and department_id in
          ?????????????????? (select department_id
          ??????????????????? from employees
          ??????????????????? where employee_id in (174,141))
          ?and employ_id not in (174,141);
          ????????????????? )
          3 using a subquery in the from clause
          ? select a.last_name,a,salary,b.slaavg
          ? from employees a ,(select department_id,
          ????????????????????? avg(salary) salavg
          ????????????????????? from?? employees
          ????????????????????? group by department_id) b
          ?? where a.department_id=b.department_id
          ?? and a.salary>b.salavg;
          4 scalar subquery expressions
          ? . a scalar subquery expression is a subquery that return exactly on column value from one row
          ? . in oracle8i scalar subqueries can be used in condition and expression part and all clause.
          ?1) sclaar subqueries in casse expression
          ?? select employee_id ,last_name,
          ?? (case
          ??? when department_id=
          ????????? (select department_id from departments
          ????????? where location_id=1800)
          ??? then 'canada'
          ??? else 'usa'
          ?? end) location
          ?from employees
          ?? 2)scalar subqueries in order by clasue
          ?? select employee_id,last_name
          ?? from employees e
          ?? order by (select department_name
          ???????????? from departments d
          ???????????? where e.department_id=d.department);
          4 correlated subqueries
          ?? the wubquery references a column form a table in the parment query
          ?? select column1,solumn2....
          ?? from table1 outer
          ?? where column1 operator
          ???????????????????????? (select column1,column2
          ????????????????????????? from table2
          ????????????????????????? where expr1=out.expr2);
          ? e.g 1
          ?? select last_name,salary,department_id
          ?? from employees outer
          ?? where salary>
          ?????????????? (select avg(salary)
          ??????????????? from employees
          ??????????????? where department_id=
          ?????????????????? outer.department_id);
          ?????????????? )
          ?? e.g 2
          ??? display details of those employees who have switched jobs at lease twice
          ??? select e.employee_id,last_name,e.job_id
          ??? from employees e
          ??? where 2<=(select count(*)
          ????????????? from job_history
          ????????????? where employee_id=e.employee_id);
          6 using the exists operator
          ? . the exists operator tests for existencee of rows in the results set of the subquery
          ? . if a subquery row value id found:
          ???? the search does not continue in the inner query
          ???? the condition is flagged true
          ? .if a subquery row value is not fount
          ???? the condition is flagged fasle
          ???? the search continues in the inner query
          ?e.g
          ??? find employees who have at least one person reporting to them
          ??? select employee_id,last_name,job_id,department_id
          ??? from employees outer
          ??? where exists (select count(*)
          ???????????????? from employees
          ???????????????? where manager_id=outer.employee_id);
          ? not exist.
          7 corelated update
          ??? use a correlated subquery to update rows in on table based on rows from another table
          ?? e.g
          ??? --denormalize the employees table by adding a column to store the department name
          ??? alter table employees
          ??? add(department_name varchar2(14));
          ?? --populate the table by using a correlated update
          ??? update employees e
          ??? set department_name=
          ?????????????????????? (select department_name
          ??????????????????????? from departments d
          ??????????????????????? where e.departmentid=d.department);
          8 correlated delete
          ??? delete test1 t1
          ??? where ster_id in(select ster_id form sales t2 where t.ster_id=t2.ster_id);?
          9 using the with clause ,you can use the same query block in a a select statement when it cocurs more than once within a complex query
          ? the with clause retrieves the results of a query block and stores it in the user's the user's templary tablespace
          ? the with clause improves performance.
          ?e.g
          ?? with
          ?? dept_costs as(
          ??? select d.department_name,sum(e.salary) as dept_total
          ??? from employee e,departments d
          ??? where e,department_id=d.department_id
          ??? group by d.department_name),
          ?? avg_cost as(
          ???? select sum(dept_total)/count(*) as dept_avg
          ???? from dept_cost)
          ? select *
          ? from dept_costs
          ? where dept_total>(select dept_avg
          ??????????????????? from afb_cost)
          ? order by department_name;

          posted @ 2006-10-11 14:43 康文 閱讀(264) | 評論 (0)編輯 收藏

          開發動態sql

          1 動態sql 簡介
          2
          ? 1 使用execute immediate 處理ddl 操作
          ??? create or replacee procedure drop_table(table_name varchar2)
          ??? is
          ???? sql_statement varchar2(100);
          ??? begin
          ?????? sql_statement:='drop table'||table_name;
          ?????? execute immediate sql_statement;
          ?? 調用
          ?????? exec drop_table('worker');
          ??? end;
          ??? 2) 使用 execute immediate 處理dcl 操作
          ??? create or replace procedure grant_sys_priv
          ??? (priv varchar2,username varchar2)
          ??? is
          ??? begin
          ???? sql_stat:='gruant'||priv||'to'||username;
          ???? execute immediate sql_stat;
          ??? end;

          ?? exec grant_sys_priv('create session','scott');
          ?? 3 使用execute immediate 處理dml 操作
          ???? 1) 處理無占位符和returning 子句的dml 語句
          ???? delcare
          ????? sql_stat varchar2(100);
          ???? begin
          ????? sql_stat:='update emp set sal=sal*1.1 where deptno=44';
          ????? execute immediate sql_stat;
          ???? end;
          ????? 2) 處理包含占位符的dml語句
          ?????? delare
          ??????? sql_stat varchar2(100);
          ?????? begin
          ???????? sql_stat:='update emp set sql=sql*(1+:percent/100)'
          ???????????????? ||'where deptno=:dno';
          ???????? execute immediate sql_stat using &1,&2;
          ?????? end;
          ????? 3) 處理包含returning 子句的dml語句
          ?????? declare
          ???????? salary number(6,2);
          ???????? sql_stat varchar2(200);
          ?????? begin
          ???????? sql_stat:='update emp set sal=sal*(1:percent/100)'
          ??????????? ||'where empno=:eno returning sal into :salary';
          ???????? execute immediate sql_stat using &1,&2;
          ??????????? returning into salary;
          ?????? end;
          ?????? 輸入1的值 15
          ?????? 輸入2的值 2222
          ?????? 新工資;2223
          ????? 4) 使用execute immediate 處理單行查詢
          ??????? declare
          ????????? sql_stat varcchar2(100);
          ????????? emp_record emp%rowtype;
          ??????? begin
          ????????? sql_stat:='select * from emp where empno=:eno';
          ????????? execute immediate sql_stat into emp_record using &1;
          ?????? end;
          ?3 處理多行查詢語句
          ?? declare
          ????? type empcurtyp is ref cursor;
          ????? emp_cv empcurtyp;
          ????? emp record emp%rowtype;
          ????? sql_stat varchar2(100);
          ?? begin
          ????? sql_stat:='select * from em where deptno=:dno';
          ????? open emp_cv for sql_stat using &dno;
          ????? loop
          ???????? fetch emp_cu into emp_record;
          ???????? exit when emp_cv%notfound;
          ????? end loop;
          ????? close emp_cv;
          ?? end;
          4 在動態sql 中使用bulk語句
          ?? 1) 在 execute immediate 語句中使用動態bulk 語句
          ???? declare
          ?????? type ename_table_type is table of emp.ename%type
          ??????? index by binary_integer;
          ?????? type sal_table_type is table of emp.sal%type
          ??????? index by binary_integer;
          ?????? ename_table ename_table_type;
          ?????? sa_table sal_table_type;
          ?????? sal_stat varchar2(100);
          ?????? begin
          ???????? sql_stat:='update emp set sal=sal*(1+:percent/100)'
          ?????????? || 'where deptno=:dno'
          ?????????? ||'returning ename,sal into :name,:salary';
          ?????? execut immediate sql_stat using &percent,&dno
          ???????? returning bulk collect into ename_table,sal_table;
          ?????? for i in 1..ename_table.count loop
          ?????? ....
          ?????? end loop;
          ???? end;
          ??? 2) 使用bulk 子句處理多行查詢
          ????? sql_stat:='select ename from emp where deptno=:dno';
          ????? execute immediate sql_stat bulk collect into ename_table using &dno;
          ??? 3) 在fetch 語句中使用bulk 子句
          ????? declare
          ??????? type empcurtyp is ref cursor;
          ??????? emp_cv empcurtyp;
          ??????? type ename_table_type is table of emp.ename%type;
          ???????? index by binary_integer;
          ??????? ename_table ename_table_type;
          ??????? sql_stat varchar2(100);
          ?????? begin
          ???????? sql_stat:='select ename from emp where job:=title';
          ???????? open emp_cv for sql_stat using '&job';
          ???????? fetch emp_cv bulk collect into ename_table;
          ??? 4) 在forall 語句中使用bulk 子句
          ????? declare
          ??????? type ename_table_type is table of emp.ename%type;
          ??????? type sla_table_type is table of emp.sal%type;
          ??????? ename_table ename_table_type;
          ??????? sal_table sal_table_type;
          ??????? sql_stat varchar2(100);
          ????? begin
          ??????? ename_table:=ename_table_type('scott','smith','clark');
          ??????? sql_stat:='update emp set sal=sal*1.1 where ename=:1'
          ??????????? ||'returning sal into :2';
          ??????? forall i in 1..ename_table.count
          ????????? execite immediate sql_stat using ename_table(i)
          ??????????? returning bulk collect into sal_table;???????
          ????? end;

          posted @ 2006-10-11 14:43 康文 閱讀(479) | 評論 (0)編輯 收藏

          managing an oracle instance

          1
          ? 1)system parameter file -- spfile<sid>,spfile (oracle 9i or later) is a binary file ,it cann't been edited by the text editor. you can change it through "alter system XXX";
          ? in oracle 9.2.0,spfile is stored in the directory of ora92\datatase\spfile<sid>.ora.
          ? 2)init parameter file(pfile)--init<sid>.ora? (early version) is a text file.it is stored in admin\<sid>\pfile.
          ?2
          ?? Entries are specific to the instance being accessed;
          ?? there are two kinds of parameters:
          ????? explicit: having an entry in the file
          ????? implicit: no entry within the file,but assuming the oracle default values;
          ?? Multiple files can be used for a single datasbase to optimize performance in different situation.
          ??? static parameter file,pfile (init.ora)
          ??? persistent parameter file,spfile(spfile<sid>.ora);
          3 order being used
          ?first spfile<sid> then int<sid>.ora
          ?select name,value from v$system_parameter
          4 spfile spfilesid.ora
          ? 1)Binary file with the abiility to make changes persistent across shutdown and startup
          ? 2)Maintained by oracle server
          ? 3)Record parameter value change made with the alter system command
          ? 4)Can specify wether the change being made is tempory or persistent
          ? 5)value can be delete or reset to allow an instance to revert to the default value;
          ??? e.g
          ??? alter system set timed_statistics=false scope=memory;
          ?? alter system set timed_statistics=false scope=spfile;
          ?? startup force-- restart oracle
          ?? select name,value from v$system_parameter where name like 'time%';
          ?? alter system set timed_statistics=false scope=both;
          ? 6) not all entries can be modified.to see more ,you can lool up v$system_parameter.in this table the isses_modifiable and issys_modifiable will tell which one? can be modified in session,and which one can be modified in sys, and which one cann't be modified.
          ?? e.g
          ?? select name,isses_modifiable from v$system_parameter where isses_modifiable='true';
          ?? alter session set timed_statistics=false;
          ?? e.g
          ?? select name,issys_modifiable from v$system_parameter where issys_modifiable<>'false';
          ??
          ?? .issys_modifiable may have two values immediate or deffered.
          ??? immediate means alter this entry will take effect on the current session ,while derrered will take effect on a new session.
          ?
          5 pfile initsid.ora
          ? .the pfile is a text file than can be modigied with an operation system editor.
          ? .modifications to the file are made manually.
          ? .changes to the file take effect on the next startup
          6 Creating an spfile
          ?? spfile can be created from initsid.ora file using thee create spfile command,whick can be executed before or after instance startup.
          ?? create spfile from pfile. -- you must shutdown the instance befofe or you can use the fellow statement:
          ??? create spfile='d:\oracle\oracle\ora92\database\spfile.ora' from pfile;
          ?yo caan backup the
          7 Oracle Managed files(OMF)
          ? 1) OMF are created and deleted by the oracle server as directed by sql commands
          ? 2) OMF are established by parameters:
          ???? DB_CREATE_DEST: set to give the default location for data files
          ???? DB__CREATE_OMLINE_LOG_DEST_N: set to gieve the default locations for online redo logs and control files,up to a mazimum of 5 locations.
          ??? e.g 1
          ??? show parameter db_create
          ??? e.g 2
          ??? create tablespace test1;--report error,Do not konw where create the data file
          ??? alter system set db_create_file_dest='d:\oracle\oradb';
          ??? create tablespace test1; -- is ok;
          ??? e.g 3
          ??? alter database add logilfe group 6;
          ??? -- if you do not specify the db_create_online_log_dest_N ,the log file will create at???? --the location which is specified by the db_create_file_dest.
          ??? e.g 4
          ??? drop table test1; -- oracle alse remove it's physicial file;
          ??? alter database drop logfile group 6-- also romove the physical file.
          ??? e.g 5
          ??? create tablespace test1
          ??? datafile 'd:\oracle\oradb\test1.dbf' size 2m;
          ??? drop tablespace test1 -- if you create tablespace or others object in this way ,you?????????????????????????? --will cann't remove the physical file.
          ??? drop table test1 including comtents and datafiles;
          8 Starting up a database mount
          ?startup nomomount :instance started for this instance;create db.create controlfule
          ???? 1) create alert_sid.log? startup log which is stored in <oracle_home>\admin\<sid>\bdump
          ???? 2) start instance include allocating memory and start bpprocess
          ??? select * from v$instance;
          ??? select * from v$bgprocess;
          ??? select * from V$sga;
          ? alter database mount;
          ??? open control files for the instance;
          ??? select* from v$database;
          ??? select* from v$tablespace;
          ??? select* from datafile;
          ??? select* from log;
          ?alter database open;
          ??? all files opened as describled by the control file for this instance;
          9 start up
          ? start pfile=...\initsid.ora;?? (alter session set nls_language=american)
          ? alter database open read only; you can not change database to read only after the database has been created.
          ? startup database restrict;
          ? alter system enable restricted session;-- only people with restricted privilege can????????????????????????????????????????? --access the database;
          ?? alter restricted session to kkk;
          ?? alter disable restricted session
          10 opening a database in read only mode
          ?? a databse can be opened as read only database alter database open read only;
          ?? a read-only database can be used to :
          ???? execute queries
          ???? execute disk sorts using locally managed
          ???? take data files offline and online ,not tableespaces
          ???? perform recovery of offline data files and tablespace;
          11Shutting down teh database
          ? normal: wait until current sessions end,wait until current trasactions end ,force a checkpoint and close files.
          ? tansactional:wail until current transaction end.force a checkpoint and close files
          ? immediate :force a checkpoint and close the files
          ? abort???? : do nothing ,just close the files. when startup ,need recovery.
          12 Managing an instance by monitoring Diagnostic Files
          ? Diagnostic files contain information about significant events encounted while the instance is operational.
          ?? .user to resolve problem or to better manager the database.
          ?? .server types of dignostic files exist:
          ????? alertsid.log? --which location is specified by the background_dump_dest?????????????????????????????????? --entry in the initsid.ora.tje default value is???????????????????? --<ora_home>\admin\sid\bdump
          ????? background trace files -- the same as above;
          ????? user_tace files
          13 alert log file
          ?? the alertsid.log file recored the command and result of major event while the database is operational.
          ?? .it is userd for day-to-day operational information or dignosing database errors
          ?? .ench entry has a time stamp associated with it.
          ?? .the dba manager the alertsid.log file.
          ?? .its location is defined by background_dump_dest.
          14 enabling or disabling user tracing
          ??? . sessin level using the alter session
          ????? alter session set sql_trace=true;
          ??? session level by execcuting dbms
          ????

          posted @ 2006-10-11 14:42 康文 閱讀(360) | 評論 (0)編輯 收藏

          archetecture query

          1 hierachical Queries
          ?select [level],colun,expr......
          ?from table
          ?[where condition(s)]
          ?[start with condition(s)]
          ?[connect by prior condition(s)]
          ?
          ?where condition
          ? exprcompparison_operator expr

          2 Starting Point
          ?.Specifies the condition that must be met
          ?.Accepts any valid condition
          3 Waling the Tree
          ? connect by prior column1=column2
          ? walk from the top donw ,using the employees table
          ?? top donw
          ???? column1=parentkey
          ???? column2=childkey
          ?? bottom up
          ???? column1=child key
          ???? column2=parent key

          ? select level,last_name
          ? from employees
          ? start with last_name='king'
          ? connect by prior employee_id=manager_id;

          posted @ 2006-10-11 14:42 康文 閱讀(187) | 評論 (0)編輯 收藏

          extension to dml in oracle

          1 over of multitable insert statements
          ?1)the insert...select statement can be userd to insert row into multiple table as part of a single dml statement.
          ?2) multitable insert statements can be used in data warehousing systems to transfer data from one or more operational sources to source to a set of target table.
          ?3) they providde significant performance improvement over
          ??? single dml versuls multiple insert...select statement
          ??? single dml versus a proceedduree to do mutiple inserts using if ,,, then syntax.
          2
          ? unconditional insert
          ? insert all
          ??? into sal_history values (EMPID,HIREDATE,SAL)
          ??? into mgr_history values (EMPID,MGR,SAL)
          ? select employee_id EMPID,hire_date JIREDATE,
          ???????? salary SAL,manager_id MGR
          ? from employees
          ? where employee_id>200;
          3 Conditional insert all
          ? insert all
          ?? when sal>1000 then
          ???? into sal_history values(empid,hiredate,sal)
          ?? when mgr>200 then
          ???? into mgr_history values(empid,mgr,sal)
          ?? select emp_id empid,hire_date hiredate,salary sal,manager_id mgr,
          ?? from employees
          ?? where employee_id>200;
          4 Conditional first insert
          ? insert first
          ??? when sal >25000? then
          ????? into special_sal values(deptid,sal)
          ??? when hiredate like ('%00%') then
          ????? into hiredate_history_00 values(deptid,hiredate)
          ??? when hiredate like ('%99%') then
          ????? insert hiredate_history_99 values(ddeptid,hiredate)
          ??? else
          ????? into hiredate_history values(deptid,hiredate)
          ??? select ddepartmeent_id deptid,sum(salary) sal,
          ???? max(hire_date) hiredate
          ??? from employees
          ??? group by department_id;
          5 Pivoting insert
          ?insert all
          ? into sales_info values (employee_id,week_id,sales_mon)
          ? into sales_info values (employee_id,week_id,sales_tue)
          ? into sales_info values (employee_id,week_id,sales_wed)
          ? into sales_info values (employee_id,week_id,sales_thur)
          ? into sales_info values (employee_id,week_id,sales_fri)
          ? select employee_id,weekid,sales_mon,sales_tue,sales_wed,sales_thur,sales_fri
          ? from sales_source_data;
          6 create index with create table statement
          ? create table new_emp
          ? (employee_id number(6)
          ???????? primary key using index
          ???????? (create index emp_id_idx on new_emp(employee_id)),
          ?? first_name varchar2(20),
          ?? last_name varchar2(25)
          ? )

          posted @ 2006-10-11 14:41 康文 閱讀(200) | 評論 (0)編輯 收藏

          Managing Passswordd Security and Resources

          1 Profiles
          ? 1)a profile is a named set of password and resource limits
          ? 2)Profiles are assigned to user by the create user or alter user command
          ? 3)can be enable or disable
          ? 4)can relate to the default profile.
          2 Password Management
          ? Password history,account locking,password expiration and aging ,password verificcation.
          3Enabling Password Management
          ? 1)set up passwordd management by using profiles and assign them to users
          ? 2)lock unlock and expire accounts usign the create user or alter user
          ? 3)alwarys enforcing
          ?? e.g
          ?? create user test identified by test;
          ?? alter user test account lock;
          ?? alter user test account unlock;
          ?? alteer user test password expire;
          4 Passowrd Account locking
          ? FAIKED_LOGIN_ATTEMPS: number of failed login attemts before lockout of the account
          ? PASSWORD_LOCK_TIME : number of days the account is locked after the specified number of??????????????????????? failed login attemps
          ? e.g
          ? create profile profile1 limit
          ? password_lock_time 1/1440? -- one muinuts
          ? failed_login_attempts 3;
          ?
          ? alter user test
          ? profile profile1;

          ? alter profile profile1 limit
          ? passowrd_lock_time 1/24? --one hour
          5 passowrd expiration and aging
          ?passwowd_life_time lifetime of the passowrd in days? after which the password expires(有效期)
          ?password_grace_time grace period in days for changing the password after the first????????????????????? successful login afteer the password has expired(鎖定期)
          ?e.g
          ?alter profile profile1 limit
          ?password_life_time 2
          ?password_grace_time 3;
          6 password history
          ?password_reuse_time:number of days before a passowrd and be resued
          ?password _reuse_max:maxum number of times password can bee reused
          ?e.g
          ?alter profile profile1 limit
          ?password_reuse_time 10
          ?password_reuse_max 3;
          7passowrd Verification(study latter)
          8drop a profile
          ?drop profile profile1 (cascade);
          the user will use the default profile.it will take effect on the new session.
          9 Resource Management
          ?Resource mangement limits can be enforced at the session level,the call level or both
          ?limits can be defined by profiles using the create profile command
          ?enable resource limints with the
          ? .resource_limit initialization parameter
          ?? alter system command
          ?e.g
          ?alter system set resource_limit=true;
          10 setting a Resdource limits at session level
          ? cup_per_session : total cpu time measured in hundredths of seconds (百分之一秒)
          ? sessions_per_user: number of coucurrent sessions allowed for each username
          ? connect_time:elapsed connect time measured in minutes
          ? idle_time :periods of inactive time measured in minutes
          ? logical_reads_per_session: number of data blocks
          ? private_sga :measure in reads
          ? e.g
          ? alter profile profile1 limit
          ? cpu_per_session 100000
          ? connect_time 60
          ? idle_time 5;
          ?
          ? alter user test profile profile1

          11 Setting Resource limits at call level?
          ?e.g
          ?alter profile profile1
          ?cpu_per_call 1000? -- cup time per call in
          ?logical_reads_per_call --number of data balock that can be read per call
          ?
          ? create profile develper_prof limit
          ?? session_per_user2
          ?? cpu_per_session 10000
          ?? idle_time 60
          ?? connect_time 480
          12 Managing Resources using database resource manager
          ?? 1)Provides the oracle server with more control over resorce management decisions
          ?? 2)elements of database resorcee manager
          ??? resource consumer group
          ??? resourcee plan
          ??? resource allocation method
          ??? resource plan directives
          ?? 3)dbms_resource_manager package is uerd to create and maintain elements
          ?? 4)requires administer_resource_manager privilege
          ??? desc dbms_resoource_manager
          13 0btaining password and resource limits informaiton
          ? information about password and resource limits can be obtained by querying the data dictonary
          ?? dba_users
          ?? select * from users;
          ?? dba_profiles
          ?? select * from dba_profiles where profile='PROFILE1'

          posted @ 2006-10-11 14:41 康文 閱讀(212) | 評論 (0)編輯 收藏

          jdbc-batch processing

          the addBatch() method is basically nothing more than a tool fro assigning a bunch of sql statements to a jdbc statement object for execution together

          PreparedStatement stmt=conn.prepareStatement(
          ????? "update account set balance=? where acct_id=?");
          int[] rows;
          for(int i=0;i<accts.length;i++){
          ??? stmt.setInt(1,i);
          ??? stmt.setLong(2,i);
          ??? stmt.addBatch();
          ? }
          rows=stemt.executeBatch();

          posted @ 2006-10-11 14:40 康文 閱讀(210) | 評論 (0)編輯 收藏

          翻頁的實現

          1 oracle 的實現
          ?語句一
          SELECT ID, [FIELD_NAME,...] FROM TABLE_NAME WHERE ID IN ( SELECT ID FROM (SELECT ROWNUM AS NUMROW, ID FROM TABLE_NAME WHERE 條件1 ORDER BY 條件2) WHERE NUMROW > 80 AND NUMROW < 100 ) ORDER BY 條件3;
          語句二:
          SELECT * FROM (( SELECT ROWNUM AS NUMROW, c.* from (select [FIELD_NAME,...] FROM TABLE_NAME WHERE 條件1 ORDER BY 條件2) c) WHERE NUMROW > 80 AND NUMROW < 100 ) ORDER BY 條件3;

          select * from (select rownum as numrow from table_name where numrow>80 and numrow<100 )
          不能直接使用 select * from rownum>100 and rownum<200;
          in oracle return null;
          2 sql server 的實現
          3 mysql 的實現

          select id from table_name where id in
          ?????????????????????????????????? select * from (select rownum as numrow ,id from tabl_name)
          ???????????????????????????????????????????? where numrow>80 and num<100;???????????????????????????????????????????
          ????????????????????????????????????????????????

          posted @ 2006-10-11 14:39 康文 閱讀(188) | 評論 (0)編輯 收藏

          jdbc-prepare sql

          1 prepared sql
          oracle provide two kinds of prepared SQL prepared statements and store procedures.Prepared SQL provide an advantage over the simple sql statements you have convered so far.if you execute the same prepared sql more than once,the database remains ready for your sql without having to rebuild the query plan.
          ?1) Prepared Statements
          ?PreparedStatement statement=conn.preparedStatement(
          ???? "update account set balance=? where id=?");
          ?for(int i=0;i<accounts.length;i++){
          ??? statement.setFloat(1,accounts[i].getBalance());
          ??? statement.setInt(2,i);
          ??? statement.execut();
          ??? stateement.clearParameters();
          ?}
          ?commit();
          ?statement.close;
          ?2) Stored Procedure
          ?try {
          ??? CallableStatement statement;
          ??? int i;
          ?
          ??? statement = c.prepareCall("{call sp_interest[(?,?)]}");
          ?
          ??? statement.registerOutParameter(2, java.sql.Types.FLOAT);
          ??? for(i=1; i<accounts.length; i++) {
          ??????? statement.setInt(1, accounts[i].getId( ));
          ??????? statement.execute( );
          ??????? System.out.println("New balance: " + statement.getFloat(2));
          ??? }
          ??? c.commit( );
          ??? statement.close( );
          ??? c.close( );
          }

          posted @ 2006-10-11 14:38 康文 閱讀(378) | 評論 (0)編輯 收藏

          java 調用存儲過程 轉載

          本文闡述了怎么使用DBMS存儲過程。我闡述了使用存儲過程的基本的和高級特性,比如返回ResultSet。本文假設你對DBMS和JDBC已經非常熟悉,也假設你能夠毫無障礙地閱讀其它語言寫成的代碼(即不是Java的語言),但是,并不要求你有任何存儲過程的編程經歷。
          存儲過程是指保存在數據庫并在數據庫端執行的程序。你可以使用特殊的語法在Java類中調用存儲過程。在調用時,存儲過程的名稱及指定的參數通過JDBC連接發送給DBMS,執行存儲過程并通過連接(如果有)返回結果。
          使用存儲過程擁有和使用基于EJB或CORBA這樣的應用服務器一樣的好處。區別是存儲過程可以從很多流行的DBMS中免費使用,而應用服務器大都非常昂貴。這并不只是許可證費用的問題。使用應用服務器所需要花費的管理、編寫代碼的費用,以及客戶程序所增加的復雜性,都可以通過DBMS中的存儲過程所整個地替代。
          你可以使用Java,Python,Perl或C編寫存儲過程,但是通常使用你的DBMS所指定的特定語言。Oracle使用PL/SQL,PostgreSQL使用pl/pgsql,DB2使用Procedural SQL。這些語言都非常相似。在它們之間移植存儲過程并不比在Sun的EJB規范不同實現版本之間移植Session Bean困難。并且,存儲過程是為嵌入SQL所設計,這使得它們比Java或C等語言更加友好地方式表達數據庫的機制。
          因為存儲過程運行在DBMS自身,這可以幫助減少應用程序中的等待時間。不是在Java代碼中執行4個或5個SQL語句,而只需要在服務器端執行1個存儲過程。網絡上的數據往返次數的減少可以戲劇性地優化性能。

          使用存儲過程

          簡單的老的JDBC通過CallableStatement類支持存儲過程的調用。該類實際上是PreparedStatement的一個子類。假設我們有一個poets數據庫。數據庫中有一個設置詩人逝世年齡的存儲過程。下面是對老酒鬼Dylan Thomas(old soak Dylan Thomas,不指定是否有關典故、文化,請批評指正。譯注)進行調用的詳細代碼:

          try{
          int age = 39;

          String poetName = "dylan thomas";

          CallableStatement proc = connection.prepareCall("{ call set_death_age(?, ?) }");

          proc.setString(1, poetName);

          proc.setInt(2, age);

          cs.execute();

          }catch (SQLException e){ // ....}

          傳給prepareCall方法的字串是存儲過程調用的書寫規范。它指定了存儲過程的名稱,?代表了你需要指定的參數。
          和JDBC集成是存儲過程的一個很大的便利:為了從應用中調用存儲過程,不需要存根(stub)類或者配置文件,除了你的DBMS的JDBC驅動程序外什么也不需要。
          當這段代碼執行時,數據庫的存儲過程就被調用。我們沒有去獲取結果,因為該存儲過程并不返回結果。執行成功或失敗將通過例外得知。失敗可能意味著調用存儲過程時的失?。ū热缣峁┑囊粋€參數的類型不正確),或者一個應用程序的失?。ū热鐠伋鲆粋€例外指示在poets數據庫中并不存在“Dylan Thomas”)

          結合SQL操作與存儲過程

          映射Java對象到SQL表中的行相當簡單,但是通常需要執行幾個SQL語句;可能是一個SELECT查找ID,然后一個INSERT插入指定ID的數據。在高度規格化(符合更高的范式,譯注)的數據庫模式中,可能需要多個表的更新,因此需要更多的語句。Java代碼會很快地膨脹,每一個語句的網絡開銷也迅速增加。
          將這些SQL語句轉移到一個存儲過程中將大大簡化代碼,僅涉及一次網絡調用。所有關聯的SQL操作都可以在數據庫內部發生。并且,存儲過程語言,例如PL/SQL,允許使用SQL語法,這比Java代碼更加自然。下面是我們早期的存儲過程,使用Oracle的PL/SQL語言編寫:

          create procedure set_death_age(poet VARCHAR2, poet_age NUMBER)

          poet_id NUMBER;

          begin SELECT id INTO poet_id FROM poets WHERE name = poet;

          INSERT INTO deaths (mort_id, age) VALUES (poet_id, poet_age);

          end set_death_age;

          很獨特?不。我打賭你一定期待看到一個poets表上的UPDATE。這也暗示了使用存儲過程實現是多么容易的一件事情。set_death_age幾乎可以肯定是一個很爛的實現。我們應該在poets表中添加一列來存儲逝世年齡。Java代碼中并不關心數據庫模式是怎么實現的,因為它僅調用存儲過程。我們以后可以改變數據庫模式以提高性能,但是我們不必修改我們代碼。
          下面是調用上面存儲過程的Java代碼:

          public static void setDeathAge(Poet dyingBard, int age) throws SQLException{

          Connection con = null;

          CallableStatement proc = null;

          try {

          con = connectionPool.getConnection();

          proc = con.prepareCall("{ call set_death_age(?, ?) }");

          proc.setString(1, dyingBard.getName());

          proc.setInt(2, age);

          proc.execute();

          }?

          finally {

          try { proc.close(); }

          catch (SQLException e) {}

          con.close();

          }

          }

          為了確??删S護性,建議使用像這兒這樣的static方法。這也使得調用存儲過程的代碼集中在一個簡單的模版代碼中。如果你用到許多存儲過程,就會發現僅需要拷貝、粘貼就可以創建新的方法。因為代碼的模版化,甚至也可以通過腳本自動生產調用存儲過程的代碼。

          Functions

          存儲過程可以有返回值,所以CallableStatement類有類似getResultSet這樣的方法來獲取返回值。當存儲過程返回一個值時,你必須使用registerOutParameter方法告訴JDBC驅動器該值的SQL類型是什么。你也必須調整存儲過程調用來指示該過程返回一個值。
          下面接著上面的例子。這次我們查詢Dylan Thomas逝世時的年齡。這次的存儲過程使用PostgreSQL的pl/pgsql:

          create function snuffed_it_when (VARCHAR) returns integer ''declare

          poet_id NUMBER;

          poet_age NUMBER;

          begin

          --first get the id associated with the poet.

          SELECT id INTO poet_id FROM poets WHERE name = $1;

          --get and return the age.

          SELECT age INTO poet_age FROM deaths WHERE mort_id = poet_id;

          return age;

          end;'' language ''pl/pgsql'';

          另外,注意pl/pgsql參數名通過Unix和DOS腳本的$n語法引用。同時,也注意嵌入的注釋,這是和Java代碼相比的另一個優越性。在Java中寫這樣的注釋當然是可以的,但是看起來很凌亂,并且和SQL語句脫節,必須嵌入到Java String中。
          下面是調用這個存儲過程的Java代碼:

          connection.setAutoCommit(false);

          CallableStatement proc = connection.prepareCall("{ ? = call snuffed_it_when(?) }");

          proc.registerOutParameter(1, Types.INTEGER);

          proc.setString(2, poetName);

          cs.execute();

          int age = proc.getInt(2);

          如果指定了錯誤的返回值類型會怎樣?那么,當調用存儲過程時將拋出一個RuntimeException,正如你在ResultSet操作中使用了一個錯誤的類型所碰到的一樣。

          復雜的返回值

          關于存儲過程的知識,很多人好像就熟悉我們所討論的這些。如果這是存儲過程的全部功能,那么存儲過程就不是其它遠程執行機制的替換方案了。存儲過程的功能比這強大得多。
          當你執行一個SQL查詢時,DBMS創建一個叫做cursor(游標)的數據庫對象,用于在返回結果中迭代每一行。ResultSet是當前時間點的游標的一個表示。這就是為什么沒有緩存或者特定數據庫的支持,你只能在ResultSet中向前移動。
          某些DBMS允許從存儲過程中返回游標的一個引用。JDBC并不支持這個功能,但是Oracle、PostgreSQL和DB2的JDBC驅動器都支持在ResultSet上打開到游標的指針(pointer)。
          設想列出所有沒有活到退休年齡的詩人,下面是完成這個功能的存儲過程,返回一個打開的游標,同樣也使用PostgreSQL的pl/pgsql語言:

          create procedure list_early_deaths () return refcursor as ''declare

          toesup refcursor;

          begin

          open toesup for SELECT poets.name, deaths.age FROM poets, deaths -- all entries in deaths are for poets. -- but the table might become generic.

          WHERE poets.id = deaths.mort_id AND deaths.age < 60;

          return toesup;

          end;'' language ''plpgsql'';

          下面是調用該存儲過程的Java方法,將結果輸出到PrintWriter:
          PrintWriter:

          static void sendEarlyDeaths(PrintWriter out){

          Connection con = null;

          CallableStatement toesUp = null;

          try {

          con = ConnectionPool.getConnection();

          // PostgreSQL needs a transaction to do this... con.

          setAutoCommit(false); // Setup the call.

          CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");

          toesUp.registerOutParameter(1, Types.OTHER);

          toesUp.execute();

          ResultSet rs = (ResultSet) toesUp.getObject(1);

          while (rs.next()) {

          String name = rs.getString(1);

          int age = rs.getInt(2);

          out.println(name + " was " + age + " years old.");

          }

          rs.close();

          }

          catch (SQLException e) { // We should protect these calls. toesUp.close(); con.close();

          }

          }

          因為JDBC并不直接支持從存儲過程中返回游標,我們使用Types.OTHER來指示存儲過程的返回類型,然后調用getObject()方法并對返回值進行強制類型轉換。
          這個調用存儲過程的Java方法是mapping的一個好例子。Mapping是對一個集上的操作進行抽象的方法。不是在這個過程上返回一個集,我們可以把操作傳送進去執行。本例中,操作就是把ResultSet打印到一個輸出流。這是一個值得舉例的很常用的例子,下面是調用同一個存儲過程的另外一個方法實現:

          public class ProcessPoetDeaths{

          public abstract void sendDeath(String name, int age);

          }

          static void mapEarlyDeaths(ProcessPoetDeaths mapper){

          Connection con = null;

          CallableStatement toesUp = null;

          try {

          con = ConnectionPool.getConnection();

          con.setAutoCommit(false);

          CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");

          toesUp.registerOutParameter(1, Types.OTHER);

          toesUp.execute();

          ResultSet rs = (ResultSet) toesUp.getObject(1);

          while (rs.next()) {

          String name = rs.getString(1);

          int age = rs.getInt(2);

          mapper.sendDeath(name, age);

          }

          rs.close();

          } catch (SQLException e) { // We should protect these calls. toesUp.close();

          con.close();

          }

          }

          這允許在ResultSet數據上執行任意的處理,而不需要改變或者復制獲取ResultSet的方法:

          static void sendEarlyDeaths(final PrintWriter out){

          ProcessPoetDeaths myMapper = new ProcessPoetDeaths() {

          public void sendDeath(String name, int age) {

          out.println(name + " was " + age + " years old.");

          }

          };

          mapEarlyDeaths(myMapper);

          }

          這個方法使用ProcessPoetDeaths的一個匿名實例調用mapEarlyDeaths。該實例擁有sendDeath方法的一個實現,和我們上面的例子一樣的方式把結果寫入到輸出流。當然,這個技巧并不是存儲過程特有的,但是和存儲過程中返回的ResultSet結合使用,是一個非常強大的工具。

          結論

          存儲過程可以幫助你在代碼中分離邏輯,這基本上總是有益的。這個分離的好處有:
          &#8226; 快速創建應用,使用和應用一起改變和改善的數據庫模式。
          &#8226; 數據庫模式可以在以后改變而不影響Java對象,當我們完成應用后,可以重新設計更好的模式。
          &#8226; 存儲過程通過更好的SQL嵌入使得復雜的SQL更容易理解。
          &#8226; 編寫存儲過程比在Java中編寫嵌入的SQL擁有更好的工具--大部分編輯器都提供語法高亮!
          &#8226; 存儲過程可以在任何SQL命令行中測試,這使得調試更加容易。

          并不是所有的數據庫都支持存儲過程,但是存在許多很棒的實現,包括免費/開源的和非免費的,所以移植并不是一個問題。Oracle、PostgreSQL和DB2都有類似的存儲過程語言,并且有在線的社區很好地支持。
          存儲過程工具很多,有像TOAD或TORA這樣的編輯器、調試器和IDE,提供了編寫、維護PL/SQL或pl/pgsql的強大的環境。
          存儲過程確實增加了你的代碼的開銷,但是它們和大多數的應用服務器相比,開銷小得多。如果你的代碼復雜到需要使用DBMS,我建議整個采用存儲過程的方式。

          posted @ 2006-10-11 14:37 康文 閱讀(194) | 評論 (0)編輯 收藏

          披著盛裝的稻草人-- 編程中的隨筆

          1 不是使用了spring ,hibernate 等企業級產品的框架,我們就是企業級產品了。不是我們采用了新瓶裝舊酒的web 2.0 我們就走在技術的前沿了。我門所需要的是一個高性能的,健壯的 產品,是一個可以降低我們實施成本,一個可以樹立我們企業品牌的產品。在這里我不得不對我們產品的所謂的架構們產品疑問,Archetectures,what are you doing?

          2 在實現框架代碼的時候,當你對采用那種實現方式猶豫不決的時,換個角度,想一想如果你是程序員,喜歡怎么這些框架。在實現框架的時候一定要考慮程序員是否能夠理解你寫框架的思路,除非萬不得已不要用一些自以為很高明很巧妙,然而卻很晦澀難懂的方法,那樣的框架,程序員至少合格的程序員是不愿意使用的。我想程序員和編碼工人最大的區別就是程序員不僅要知其然,還要知其所以然。

          3 只有在不斷實踐中,才能激發你不斷的求知欲。只有把學到的知識不斷的應用道實踐中,你才能在學習中得到滿足。不要為了學習而學習(學院派,不好聽點就是紙上談兵),而是要從實際問題出發,在解決問題的過程中不斷深入,不斷總結,所以說,當你離開了編程的第一線,你將失去學習編程知識的欲望。當然如果你愿意,在別的領域還有更廣闊的天空,但是請不要總是說自己原來編程怎么怎么,其實你已經被三振出局了。

          4 想外行一樣思考,想專家一樣實踐,一本書的名字,雖然書沒有看過,但她的名子就已經非常有意思了。這豈不就是我們作需求,和作架構時的座右銘嗎?既能象“外行”一樣的站在客戶的角度思考問題,又能象“專家”一樣參與到整個產品的開發和實施當中,在實踐中不斷提高自我。然而,不幸的是許許多多的所謂的架構師,系統分析員們卻正向著相反的方向邁進?!罢嬲钡淖龅搅?,象“專家”一樣思考,象“外行”一樣實踐,可悲呀可悲。
          5設計做到什么樣才叫做到位呢。我想只有真正的開發者才有權利發言。只有有它們才是設計的真正使用者和受害者。因為就我所知和所見,絕大多數設計都是設計者自己的游戲(當然,我可能是井底之蛙了沒有見過什么好的設計),程序員所開發往往還是對著原形自己再進行一遍設計,且不說額外增加了多少工作量,浪費了多少時間,就工作質量而言,也是差強人意。畢竟大多數情況下,設計者或稱為架構師的在技術方面的經驗都更為豐富,對業務的理解也更為深入,另外由一個人進行設計在功能復用,和整體性能方面的考慮也更完整一些。但怎么做才能熊掌和魚兼得呢?下面我發表一下我個人的看法:
          ? 1 代碼就是最好的設計,這句話不是我說的,是 xp開發屆 中的一位大牛說的。之所以在這里引用別人的觀點,并不是自己是一個xp 的fans,也并不時完全贊同xp 的理論,我只是覺得這句話得太對了,對程序員來說什么設計比代碼讀起來更親切呢?。其實設計無非是向開發所著傳達設計者的思想,告訴開發者系統需要開什么個對象,具有什么屬性和行為,它們之間的調用關系又如何。我們在設計文檔中經常使用的方法就是有class 圖,協作圖,和順序圖對上面所提到的進行描述。然而結果呢,面對這大量的令人畏懼的抽象圖表,開發者可選擇的也只有是“重整江河待后生了”。想想,這樣的設計和代碼能夠同步嗎,這樣的設計文檔還有什么用呢?所以說與其是這樣還不如把設計變成代碼,如對象屬性可以這直接在代碼中體現,方法可以只定義接口,實現方式可以作為代碼的注釋,向寫需求分析用例似的來一步一步說明程序是需要怎樣調用。當客戶要求設文檔的時候,只需要提出javadoc就可以了,而其保證和代碼同步。而開發者呢,在開發前需要閱讀用例,了解需求,然后在設計者已經搭好的代碼框架中進行開發就可以了。如果需要修改的話,不用在去設計文檔中更改,只需要修改一下代碼注釋就可以了,(程序員是比較懶的,不怎么愿意寫寫文檔的)。當然了,讓懶惰的程序員能夠自覺地寫好文檔也不是一件容易事,下面也許能給你提供一個好的方法
          ? 2 交差開發能夠幫助完成最好的設計文檔。
          ? 3 設計者在開發階段還作什么呢??????????????????
          待續???????????????????????????????????????????????????????????????

          posted @ 2006-10-11 14:36 康文 閱讀(242) | 評論 (0)編輯 收藏

          access controll

          1Privilgeges
          ?1) Database security:
          ? --System security
          ? --Data security
          ?2)System privileges:Caining access to the database
          ?3)Object privileges:manipulationg thee content of the database objects
          ?4)Schemas:Collections of objects ,such as tables,views,and sequences
          2System Privileges
          ? . More than 100 privileges are available;
          ? . The database administrator has high-levle system privileges for tasks such as:
          ??? creating new user,removing user,removing tables,backing up tables
          3 Creating user
          ?the dba creates users by using the create user statement
          ?create user user
          ?identified by password;
          ?e.g create user object scott
          ???? identified by tiger;

          ?SQL> create user testuser
          ? 2? identified by test;

          User created

          SQL> conn testuser/test@orcl2000
          Not logged on

          SQL> grant access session to testuser;

          grant access session to testuser

          Not logged on

          SQL> conn digit_cc/digit_cc@orcl2000
          Connected to Oracle9i Enterprise Edition Release 9.2.0.1.0
          Connected as digit_cc

          SQL> grant create session to testuser;

          Grant succeeded

          SQL> conn testuser/test@orcl2000;
          Connected to Oracle9i Enterprise Edition Release 9.2.0.1.0
          Connected as testuser
          4 user System privileges
          ?once a user is created,the dba can grant specific system privileges to a user
          ?grant privilege[,privilege...]
          ?to user [,user|role,public...];

          ?DBA can grant a user specific system privileges
          ?grant create session,create table,create sequence,create view? to scott;
          5 creating and granting privileges to role
          ' Create a role
          ? create role manager;
          ?.grant privileges to a role
          ? grant create table,create view to manager
          ?.Grant a role to user
          ? grant manager to kochar;
          ?
          SQL> create role testrole;

          Role created

          SQL> grant create table,create view,create sequence to testrole;

          Grant succeeded

          SQL> grant testrole to testuser;
          6 change your password
          ?you can change your password by using the alter user statement;
          ?alter user scott
          ?indetified by lion;
          7 object privileges
          ?object privileges vary from object to object
          ?an owner has all the privilege to the object
          ?an owner can give specific privilege on that owner object
          ? grant select on auther to testuser;
          ? grant select on outher to testuser with grant option -- testuser also can grant it to

          other user;
          ? grant update(department_name,location_id)
          ? on departments
          ? to scott,manager;
          8 how to revoke object privileges
          ?--you use the revoke statement to revoke privileges granted to other users
          ?--privileges granted to other users through the with grant option clause are also revoked.
          ? revoke privilege {[,privilege...]|all} on object
          ? from {user[,user....]|role|public}
          ? [cascade constraints]
          ? revoke select on author from user;
          9 Database Links
          ?Database link allow user to access data in the remote database;
          SQL> create database link kjw1
          ? 2? connect to digit_cc identified by digit_cc
          ? 3? using 'orcl2000';

          Database link created

          SQL> select * from digit_cc.table_action@kjw1;

          posted @ 2006-09-29 15:40 康文 閱讀(239) | 評論 (0)編輯 收藏

          database link 使用 轉載

          鏈接到遠程數據庫

          在一個分布式的環境里,數據庫鏈接是定義到其它數據庫的路徑的一個重要方法,使得遠程處理天衣無縫。

          要獲得數據庫鏈接的更深奧的知識,查看Oracle8i SQL Reference(Oracle8i SQL參考)和Oracle8i Concepts (Oracle8i概念手冊)。詳細資料的另一個極好的來源是Oracle8i Distributed Database Systems(Oracle8i分布式數據庫系統手冊)。

          今天許多運行Oracle的機構有不止一個Oracle數據庫。有時不管原計劃是否這樣,一個數據庫中的數據可能與另一數據庫中的數據關聯。出現這種情況時,你可以鏈接這兩個數據庫使得用戶或應用程序可以訪問所有數據,就好象它們在一個數據庫中。當你這么做時,你就有了一個分布式數據庫系統。

          如何將兩個數據庫鏈接在一起呢?使用一個數據庫鏈接來完成。數據庫鏈接是定義一個數據庫到另一個數據庫的路徑的對象。數據庫鏈接允許你查詢遠程表及執行遠程程序。在任何分布式環境里,數據庫鏈接都是必要的。

          簡單案例

          數據庫鏈接的目的是定義一條到遠程數據庫的路徑,使你可以通過在本地執行一條SQL語句來使用那個數據庫中的表和其它的對象。例如,你在一個遠程數據庫上有一個稱之為"geographic feature name"的表,而你想在已連接到你本地數據庫的情況下訪問那些數據。數據庫鏈接正是你所需要的。在建立它之前,你必須搜集如下信息:

          一個網絡服務名稱,你的本地數據庫事例能夠使用它來與遠程事例相連接遠程數據庫上的有效用戶名和口令網絡服務名稱是每一個數據庫鏈接必需的。每一次你從客戶機PC使用SQL*Plus連接到你的數據庫時都要使用服務名稱。在那些情況下,你提供給SQL*Plus的網絡服務名稱是通過在你的客戶機上的nsnames.ora文件中查找它們來解析的。在數據庫鏈接中使用的網絡服務名稱也是如此,除非是那些名字是使用駐留在服務器上的tnsnames.ora文件來解析。

          在你定義數據庫鏈接時指定的用戶名和口令,用于建立與遠程事例的連接。不需硬編碼用戶名和口令,建立數據庫鏈接也是可能的甚至是值得選取的。既然這樣,現在我們注意這個最直接的例子。

          下列語句建立了一個數據庫鏈接,它允許訪問客戶帳戶,這個帳戶是事先在GNIS數據庫建好的:

          CREATE DATABASE LINK GNIS
          CONNECT TO GUEST IDENTIFIED BY WELCOME
          USING 'GNIS';

          鏈接名稱GNIS緊隨LINK關鍵字。當連接到遠程事例時,CONNECT TO...IDENTIFIED子句指定UEST/WELCOME作為用戶名和口令使用 。USING子句指定通過網絡服務名稱GNIS建立連接。使用這一鏈接,現在你可以在遠程數據庫上查詢數據。例如:

          SQL> SELECT GFN_FEATURE_NAME
          2 FROM GNIS.FEATURE_NAMES@GNIS
          3 WHERE GFN_FEATURE_TYPE='falls'
          4 AND GFN_STATE_ABBR='MI'
          5 AND GFN_COUNTY_NAME='Alger';

          GFN_FEATURE_NAME
          _________________
          Alger Falls
          Au Train Falls
          Chapel Falls
          Miners Falls
          Mosquito Falls
          Tannery Falls
          ..

          在SELECT語句中@GNIS緊隨表名稱,說明GNIS.FEATURE_NAMES表是在遠程數據庫,應該通過GNIS鏈接訪問,鏈接類型Oracle支持幾種不同類型的鏈接。這些類型相互重疊,有時難以通過選項進行分類。當你建立數據庫鏈接時,你需要從下面選?。?

          Public(公用)或Private (私有)鏈接

          權限類: Fixed User(固定用戶), Connected User(連接用戶)或 Current User(當前用戶)
          Shared Link(共享鏈接)或 Not Shared Link(非共享鏈接)
          每次創建數據庫鏈接時,你要自覺不自覺地做這三種選擇。


          公用鏈接與私有鏈接相對比

          公用數據庫鏈接對所有的數據庫用戶開放訪問權。前面顯示的是私有數據庫鏈接,它只對建立它的用戶授權。公用數據庫鏈接更為有用,因為它使你不必為每一個潛在用戶創建單獨的鏈接。為了建立一個公用數據庫鏈接,使用如下顯示的PUBLIC關鍵字:

          CREATE PUBLIC DATABASE LINK GNIS
          CONNECT TO GUEST IDENTIFIED BY WELCOME
          USING 'GNIS';

          即使這是一個公用鏈接,用戶名仍舊固定。所有使用這個鏈接的用戶都作為用戶GUEST連接到遠程數據庫。


          使用數據庫鏈接訪問遠程表

          圖1 數據庫鏈接GNIS,指明網絡服務名稱,鏈接PROD事例到GNIS事例中的FEATURE_NAMES表。


          權限類

          當你建立一個數據庫鏈接時,關于你如何授權對遠程數據庫進行訪問,有三種選擇。這三種選擇代表了數據庫鏈接的另一種分類方法。這三種類別如下:

          固定用戶。為遠程數據庫鏈接指定用戶名和口令,作為數據庫鏈接定義的一部分。
          連接用戶。在不指定用戶名和口令時創建的數據庫鏈接。
          當前用戶。建立數據庫鏈接并指定CURRENT_USER關鍵字。
          固定用戶數據庫鏈接是指在創建鏈接時為遠程數據庫指定用戶名和口令。這一鏈接不管什么時候使用,也無論誰使用,都使用相同的用戶名和口令登陸到遠程數據庫。到目前為止你在本文中所看到的都是固定用戶鏈接。

          固定用戶鏈接,尤其是公用固定用戶鏈接的一個潛在問提是他們把遠程系統上的同一帳戶給了許多本地用戶。從安全角度來說,如果所有的本地用戶在遠程系統上擁有同一個帳戶,責任就要折中,這取決于用戶的數量 。如果數據丟失,幾乎不可能確定破壞是如何發生的。另一個潛在問題是公用固定用戶鏈接將對遠程數據庫的訪問權給了所有的本地數據庫用戶。

          如果你不想在數據庫鏈接中嵌入用戶名和口令,Oracle提供給你另一個非常有用的選擇。你可以建立一個連接用戶鏈接。連接用戶鏈接是這樣的鏈接,它通過任一個正在使用該鏈接的本地數據庫的用戶的用戶名和口令登陸到遠程數據庫。你可以通過簡單地空出用戶名和口令來建立一個連接用戶鏈接??紤]如下定義:

          CREATE PUBLIC DATABASE LINK GNIS

          USING 'GNIS';

          鏈接名是GNIS。它連接到遠程數據庫連接時使用的網絡服務名稱是GNIS,但是沒有指定用戶名和口令。當你在查詢中使用這個鏈接時,它將向遠程數據庫發送你當前的用戶名和口令。例如,如果你使用AHMAD/SECRET 登陸到你的本地數據庫,那么AHMAD/SECRET將是你登陸到遠程數據庫時使用的用戶名和口令。

          為了使用一個連接用戶鏈接,你必須在遠程數據庫上有一個帳號,了解這一點是很重要的。不但這樣,而且你在兩個數據庫上應使用同樣的用戶和口令。如果本地登陸使用AHMAD/SECRET,那么登陸到遠程數據庫時也必須使用同樣的用戶名和口令。使用連接用戶鏈接時,如果你的口令不同,你就無權登陸。

          公用連接用戶數據庫鏈接尤其有用,因為你可以建立一個可被所有用戶訪問的鏈接,并且所有用戶被分別使用他或她自己的用戶名和口令授權。你獲得責任方面的利益,沒有將遠程數據庫向你的本地數據庫上的每一位用戶開放。代價是你必須在兩個數據庫上建立用戶帳戶,并且你必需確信口令保持一致。

          當前用戶鏈接通過使用CURRENT_USER關鍵字建立并且與連接用戶鏈接相似。只有當使用Oracle Advanced Security Option(Oracle高級安全選項)時,你才能使用當前用戶鏈接,這個鏈接只對授權使用X.509認證的用戶有用。


          共享鏈接

          共享數據庫鏈接是指該鏈接的多個用戶可以共享同一個底層網絡連接。例如,在有四位用戶的MTS(多線程服務器)環境下,每一個共享服務器進程都將與遠程服務器有一個物理鏈接,這四位用戶共享這兩個鏈接。
          表面上,共享鏈接乍一聽起來像是一件好事。在某些環境下的確如此,但是,當你考慮使用共享鏈接時,應當意識到這有許多局限性和警告:


          如果你使用一個專用的服務器連接來連接到你的本地數據庫,鏈接只能在你從那些連接中創建的多重會話間共享。 在MTS環境里,每一個共享服務器進程潛在地打開一個鏈接。所有的會話被同一共享服務器進程提供并且分享被那個進程打開的任意共享鏈接。因為在MTS環境里的一個共享服務器進程能夠服務于許多用戶連接,共享鏈接的使用可能導致打開的鏈接遠多于所必須的鏈接。用SHARED關鍵字建立共享數據庫鏈接。還必須使用AUTHENTICATED BY 子句在遠程系統上指定一有效的用戶名和口令。如下命令建立一個共享的、公用的、連接用戶數據庫鏈接:


          CREATE SHARED PUBLIC DATABASE LINK GNIS
          AUTHENTICATED BY DUMMY_USER IDENTIFIED BY SECRET
          USING 'GNIS';

          要獲得創建鏈接和管理分布式系統的更多資料,請查閱Oracle Technology Network (http://otn.oracle.com/)。
          使用AUTHENTICATED BY子句稍微有些困擾,但是由于實現共享鏈接的方式安全性決定它是必須的。這個例子中的用戶名和口令DUMMY_USER/SECRET必須在遠程系統上有效。然而,遠程系統上使用的帳戶仍就是連接用戶的帳戶。如果我以JEFF/SECRET登陸到我的本地數據庫并使用我剛建好的共享鏈接,將會發生以下一系列事件:


          為了打開鏈接,Oracle使用DUMMY_USER/SECRET向遠程數據庫授權。 然后,Oracle試圖使用HMAD/SECRET使我登陸到遠程數據庫。共享鏈接的主要目的是減少兩個數據庫服務器之間的底層網絡連接數量。它們最適合于MTS環境,在那你擁有大量的通過這一鏈接訪問遠程數據庫的用戶。觀念上,你想讓用戶數量超過共享服務器進程的數量。那么你可以通過為每一共享服務器進程打開一個鏈接而不是每位用戶打開一個鏈接的方法,節省資源。


          查找關于數據庫鏈接的資料

          你可以從幾個數據字典視圖中獲得建立好的數據庫鏈接的資料。DBA_DB_LINKS視圖為每一定義的鏈接返回一行。OWNER 列和DB_LINK列分別顯示了這一鏈接的所有者及名稱。對公用數據庫鏈接,OWNER列將包含'PUBLIC'。如果你建立固定用戶鏈接,用戶名應在DBA_DB_LINKS視圖的USERNAME列里,但是口令只能從SYS.LINK$視圖中看到。默認情況下,只有具有SELECT ANY TABLE系統權限的DBA能夠訪問SYS.LINK$視圖查看口令。你應該保護訪問那個視圖的權限。ALL_DB_LINKS 視圖和 USER_DB_LINKS視圖與 DBA_DB_LINKS視圖相類似-它們分別顯示了你能夠訪問的所有鏈接及你所擁有的全部鏈接。最后,V$DBLINK動態性能視圖向你顯示出任意給定時間你-當前用戶,打開的全部數據庫鏈接。


          全局性的數據庫名稱

          在分布式環境里,Oracle建議你的數據庫鏈接名應與它們連接到的數據庫的全局性名稱相匹配。因此如果你正在連接到名稱為GNIS.GENNICK.ORG的數據庫,你應當將你的數據庫鏈接命名為GNIS.GENNICK.ORG
          為確定數據庫的全局性名稱,以SYSTEM登陸并查詢GLOBAL_NAME視圖:


          SQL> SELECT * FROM GLOBAL_NAME;

          GLOBAL_NAME
          _______________
          GNIS.GENNICK.ORG

          由于歷史的原因,默認情況下,全局性名稱與數據庫鏈接名稱的之間的鏈接不是強制性的。不過,你可以通過設置GLOBAL_NAMES的初始化參數為TRUE來改變這一行為。例如:


          SQL> SHOW PARAMETER GLOBAL_NAMES

          NAME TYPE VALUE
          ________________________________________________________
          global_names boolean TRUE

          用于產生這個范例的事例要求你使用的數據庫鏈接名,必須與目標數據庫的全局性數據庫名稱相匹配。注意與一些Oracle文檔中說的相反,關鍵是你的本地事例的GLOBAL_NAMES設置。如果你的本地事例中GLOBAL_NAMES=FALSE,你就能夠使用數據庫鏈接,而不用管它們是否與遠程數據庫的全局性名稱相匹配??偟膩碚f,如果你設置GLOBAL_NAMES=TRUE,你應該在你的所有事例中一律這么做。

          posted @ 2006-09-29 15:35 康文 閱讀(2147) | 評論 (0)編輯 收藏

          some database object

          1 sequence
          ? 1)?? automatically generatess unique numbers
          ?? is a sharable object
          ?? is typically used to create a primary key value
          ?? replaces applicaition code
          ?? speeds up the efficiency of accessing sequence
          ?? create sequence sequence
          ?? [increment by n]
          ?? [start with n]
          ?? [{maxvalue n |nomaxvalue}]
          ?? [{minvalue n |nominvalue}]
          ?? [{cycle|nocycle}]
          ?? [{cache n |nocache}]

          ?? create sequence dept_deptin_seq
          ?? increment by 10
          ?? start with 120
          ?? maxvalue 9999
          ?? nocache
          ?? nocycle
          ? 2) Confirming Sequences
          ?? verify your sequence values in the user_sequences data dictionary table
          ?? select sequence_name,min_value,max_value,increment_by,last_number
          ?? from user_sequences;
          ?? the last_number display the next available sequence number if nocache is specified
          ? 3)nextval and currval Pseudocolumns
          ??? --nextval return thee next available sequence value,it return a unique value every time
          it si referenced,even for different ueer;
          ??? --currval obtains the current sequence value;
          ??? --nextval must be issued for that sequence before curval contains a value;
          ? 4) Using a Sequence
          ??? -- Caching sequence values in the memory give faster access to these values;
          ??? -- Gaps in sequence value can occur when
          ?????? a rollback occurs
          ?????? b the system crashes
          ?????? c A sequence us used in another table;
          ?? 5) alter sequence test increment by 10;
          ????? you can change all properties of the sequence except the start with .
          ?? 6) remove sequence
          ????? drop sequence test;
          2 index
          ? 1) how are indexes created
          ?? Automatically : a unique index is created automatically when you create primary key or

          unique constraint in a table definition,
          ?? Manually: user can create nounique index on column to speed up access to the rows.
          ?? create index testindex on autoer(lanme);
          ? 2) When to Create an index
          ?? ypu should create an index if:
          ?? . a column contains a wide range of values
          ?? . a column contains a large number of null values
          ?? . one or more columns are frequently used together in where clause or a join condition;
          ?? . The table is large and most queries are expected to retrieve less than 2 to 4 percent

          of the rows;
          ?? 3) When not to create an index
          ?? this usually not worth creating an index if:
          ?? . the table is small
          ?? . The columns are not often used as a condition in the query.
          ?? . Most queries are expected to retrieve more than 2 to 4 percent of the rows in the

          table
          ?? . the indexed columns are referenced as part of an expression.
          ?? 4)Confirming indexes
          ??? . The user_indexes data dictionary view contains the name of the index and tis uniquess
          ??? . the user_ind_columns view contains the index name,the table name,and the column name.
          ??? select ic.index_name,ic_column_name,ic.column_position,ic_col_pos,ix.uniqueness
          ??? from user_indexed ix,user_ind_columns ic
          ??? where ic.index_name=ix.index_name
          ??? and ic.table_name='employees';
          ? 5)基于函數的索引
          ? . a function-based index is an index based on expressions
          ? . The index expression is built form table columns,constraints,SQL functions and user-

          defined functions
          ?? create index testindex2
          ?? on autors (upper(au_fname));
          ??
          ?? select * from authors
          ?? where upper(au_fname) like 'B%';
          ? 6) remoe index
          ?? drop index index_name;
          3 synonyms
          ? Simplify access to objects by creating a synonym
          ?? . Ease referring to a table ownerd by anther user
          ?? . Shorten lengthy object names;
          ?? create [publi] synonym synonym for object;

          posted @ 2006-09-29 11:31 康文 閱讀(191) | 評論 (0)編輯 收藏

          使用游標

          1 pl/sql 集合 處理單列多行數據庫,使用的類型為標量類型
          ?1) 索引表
          ? type ename_table_type is table of emp.ename%type
          ??? index by binary_integer;
          ? ename_table ename_table_type;
          ? begin
          ??? select ename into ename_table(-1) from emp
          ????? where empno=&no;
          ??? dbms_output.put_line('雇員名:'||ename_table(-1));
          ? end;
          ?
          ?? set serveroutput no
          ?? declare
          ???? type area_table_type is table of number
          ??????? index by varchar2(10);
          ???? rea_table area_table_type;
          ??? begin
          ??????? area_table('beijing'):=1;
          ??????? area_table('shanghai'):=2;
          ??????? area_table('guangzhou'):=3;
          ??????? dbms_output.put_line(area_table.first);
          ??????? dbms_output.put_line(area_table.last);
          ??? end;
          ???? 2) 嵌套表
          ????? 索引表類型不能作為累得數據類型使用,但是嵌套表可以作為表類的數據類型使用。
          當使用嵌套表元素時,必須先用其構造方法初始化其嵌套表:
          ?????? a? 在pl/sql 塊中使用嵌套表
          ??????? declare
          ????????? type ename_table_type is table of emp.ename%type;
          ????????? ename_table ename_table_type;
          ??????? begin
          ?????????? ename_table:=eanme_table_type('2','2','3');
          ?????????? select ename into ename table(2) from emp where empno=&no;
          ?????????? dbms_ouput.put_line(ename_table(2));
          ??????? end;
          ????? b 在表中使用嵌套表
          ??????? create type phone_type is table of varchar2(20);
          ??????? create table employee(
          ????????? id number (4),name varchar2(10),sal number(6,2),
          ????????? phone phone_type
          ??????? )nested table phone store as phone_table;
          ?????? -- 為嵌套表插入數據
          ??????? insert into employee values(2,'scott',200,phone_type('2222','333333'));
          ?????? --檢索嵌套表累得數據
          ??????? set erveroutput on
          ??????? declare
          ????????? phone_table phone_type;
          ??????? begin
          ????????? select phone into phone_table
          ????????? from employee where id=1;
          ????????? for i in 1..phone_table.count loop
          ??????????? dbms_output.put_line(phone_table(i));
          ????????? end loop;
          ??????? end;
          ?????? -- 更新嵌套表列的數據
          ???????? delcare
          ??????????? phone_table phone_type:=('44444','555555');
          ???????? begin
          ??????????? update employee set phone=phone_table
          ??????????? where id=1;
          ???????? end;
          ??? 3) 變長數組
          ????? 在使用varray 時必須指定最大個數,和數據類型,在使用其元素時必須進行初始化
          ????? type ename_table_type is varray(20) of emp.ename%type;
          ????? ename_table ename_table_type:=ename_table_type('1','2');
          ?????
          ????? -- 在快中使用varray
          ????? declare
          ???????? type ename_table_type is varray(20) of emp.ename%type;
          ???????? ename_table ename_table_type:=ename_table_type('mary');
          ???????? begin
          ??????????? select ename into ename_table(1) form emp
          ?????????????? where empno=$no;
          ????????? end;
          ????? --在表列中使用varray
          ?????? create type phone type is varray(20) of varchar2(20);
          ?????? create table employee(
          ???????? id number(4),name varchar2(10),
          ???????? sal number(6,2),phone phone_type);
          ??????
          ???? 3)記錄表
          ????? 記錄表結合了記錄和集合的優點
          ??????? declare
          ????????? type emp_table_type is table of emp%rowtype
          ????????? index by binary_integer;
          ??????? emp_table emp_table_type;
          ??????? begin
          ????????? select * from into emp_table(1) from emp
          ????????? where empno=&no;
          ????????? dbms_output.put_line(emp_table(1).ename);
          ??????? end;
          ????? 4)多維集合
          ?????? 1 多級varray
          ?????? declare
          ??????? --define 一維集合
          ????????? type al_array_type is varray(10) of int;
          ??????? --定義二維集合
          ????????? type nal_varray_type is varray(10) of a1_varray_type;
          ??????? --初始化二維集合
          ????????? nvl nal_varray_type:=nal_varray_type(
          ??????????? a1_varray_type(1,2),
          ??????????? a1_varray_type(2,3)
          ????????? )
          ???????? beign
          ?????????? for i in 1..nal_varray_type.count loop
          ????????????? for j in 1..a1_array_type.count loop
          ??????????????? dbms_out.putline(nvl(i)(j));
          ????????????? end loop;
          ?????????? end loop;
          ??????? end;
          ?????? 2 使用多級嵌套表
          ??????? table a1_table_type is table of int;
          ??????? table nvl_table_type is table of a1_table_type;
          ??????? nvl nvl_table_type:=nvl_table_type(
          ????????? a1_table_type(1,2),
          ????????? a1_table_type(2,3)
          ??????? );
          2 集合方法
          ? 1) exist
          ?? if ename_table.exists(1) then
          ??? ename_table(1):='scott';
          ?? 2) count 返回當前集合變量中的元素總個數
          ??? ename_table.count
          ?? 3) limit 返回集合元素的最大個數? 只有varray 有
          ?? 4)first and last
          ?????? ename_table.first
          ?????? ename_table.last
          ?? 5) prior 和next
          ??? ename_table.prior(5); --返回元素5的前一個
          ??? ename_table.next(5);? --? 后一個
          ?? 6) extend
          ??? 使用于varray 和 嵌套表。
          ??? extend add a null value
          ??? extend (n) add n null value
          ??? extend (n,i)add n i value
          ??? declare
          ????? type ename_table_type is varray(20) of varchar2(20);
          ????? ename_table ename_table_type;
          ??? begin
          ????? ename_table:=ename_table_type('mary');
          ????? ename_table.extend(5,1);
          ????? dbms_output.put_line(ename_table.count);
          ??? end;
          ?? 7) trim
          ?? trim remove one element from the tail of the collection.
          ?? trim(n) remove n element from the tail of the colleciton.
          ?? 8)delete
          ??? delete: delete all the elements
          ??? delete(n) :delete the nth elements
          ??? delete(m,n): delete the elements from m to n
          3 集合賦值
          ? 1)將一個集合的數據賦值給另一個集合.clear the destination collectins and set the original collection
          ?? delcare
          ??? type name_varray_type is varray(4) of varchar2(10);
          ??? name_array1 name_varray_type;
          ??? name_array2 name_varray_type;
          ?? begin
          ???? name_array1:=name_varray_type('scott','smith');
          ???? name_array2:=name_array_type('a','b','c');
          ???? name_array1:=name_array2;??
          ?? end;
          ??
          ?
          ? type name_array1_type is varray(4) of varchar2(10);
          ? type name_array2_type is varray(4) of varchar2(10);
          ? name_array1 name_array1_type;
          ? name_array2 name_array2_type;
          ? 具有相同的數據類型,單具有不同的集合類型不能構賦值
          ? 2) 給集合賦城null 值
          ??? 可以使用delete 或 trim
          ??? 也可以使用 空集合賦給目表集合
          ??? type name_varray_type is varray(4) of varchar2(10);
          ??? name_array name_varray_type;
          ??? name_empty name_varray_type;
          ???
          ??? name_array:=name_varray_type('1','2');
          ??? name_array:=name_empty;
          ? 3) 使用集合操作賦和比較集合都是10g 的內容,p176 先略過。
          4 批量綁定
          ? 執行單詞sql 操作能傳遞所有集合元素的數據。
          ? 1 forall 語句
          ? 用于insert update 和delete操作。在oracle9i 中forall 語句必須具有連續的元素
          ??? 1) using forall on insert
          ???? declare
          ??????? type id_table_type is table of number(6)
          ??????? index by binary_integer;
          ??????? type name_table_type is table of varchar2(2)
          ??????? index by binary integer;
          ??????? id_table id_table_type;
          ??????? name_table name_table_type;
          ????? begin
          ???????? for i in 1..10 loop
          ?????????? id_table(i):=i;
          ?????????? name_table(i):='Name'||to_char(i);
          ???????? end loop;
          ???????? forall i in 1..id_table.count
          ?????????? insert into demo demo values(id_table(i),name_table(i));
          ????? end;
          ???? 2)using forall on using update
          ?????? forall i in 1..id_table.count
          ?????????? upate demo set name:=name_table(i)
          ????????????? where id:=id_table(i);
          ???? 3)using forall on using delete
          ??????? forall i in 1..id_table.count
          ??????????? delete from demo where id:=id_table(i);
          ???? 4) using forall on part of the collection
          ??????? for i in1..10 loop
          ????????? id_table(i):=i;
          ????????? name_table(i):="name"||to_char(i);
          ??????? end loop;
          ??????? forall i in 8..10 l
          ?????????? insert into demo values(id_table(i),name_table(i));
          ?? 2 bulk collect
          ???? is fit for select into ,fetch into and dml clause
          ???? 1) using bulk collect
          ????? declares??
          ??????? type emp_table_type is table of emp%rowtype
          ???????? index by binary_integer;
          ??????? emp_table emp_table_type;
          ????? begin
          ???????? select * bulk collect into emp_table
          ????????? from emp where deptno=&no;
          ???????? for i in 1..emp_tablee.count loop
          ??????????? dbms_output.put_line(emp_table(i).ename);
          ???????? end loop;
          ????? 2) 在dml 的返回字句使用bulk collect 字句
          ???????? declare
          ????????? type ename_table_type is table of emp.ename%type;
          ?????????? ename_table ename_table_type;
          ????????? begin
          ???????????? deletee from emp where deptno=&no
          ???????????? returning ename bulk_collect into ename_table;
          ????????? for i in 1..ename_table.count loop
          ??????????? dbms_output.put(ename_table(i));
          ????????? end loop;
          ??????? end;
          ????????? end;
          ????? end;

          posted @ 2006-09-28 15:32 康文 閱讀(153) | 評論 (0)編輯 收藏

          createing view

          1Why Use Views
          ? to restrict data access
          ? to make complex query easy
          ? to provide data independence
          ? to provide defferent view of the same data
          2 Creating a View
          ? 1)create [or replace] [force|noforce] view view
          ? as subquery
          ? force : create view wether the referenced object existed or not
          ?
          ? desc view_name;
          ?2)create a view by using column aliases in the subquery
          ? create view salv50
          ? as select employee_idIO_NUMBER,last_name NAME,slaary*12 ANN_SALARY
          ? from employees
          ? where department_id=50;
          3 Modigy a View
          ? 1) Modigy the emplvu80 view by using create or replace view clause.Add an alias for each

          column name;
          ?? create or replace view empvu80
          ?? (id_number,name,sal,department_id)
          ?? as select employee_id,first_name||" "||last_name,salary.department_id
          ?? from employees
          ?? where department_id=80;
          ?? column aliases in the create view clause are listed in the same order as the columns in

          the subquery
          ?? note : alter view_name is not a valid command.
          4 Create a Complex View
          ? Create a complex view that contains group functions to display values from two tables
          ? create view dept_sum_vu
          ?? (name,minsal,maxsal,avgsal)
          ? as
          ?? select d.department_name,min(e.salary),max(e.salary),avg(e.salary)
          ?? from employees e,departments d
          ?? where e.department_id=d.department_id
          ?? group by d.department_name;
          5 Rules for performs DML operaton on a view
          ? 1) You can perform DML operation on simple views
          ? 2) You can not romove a row if the view contains the following:
          ??? --group functions
          ??? --a group by clause
          ??? --the distince keyword
          ??? -- rownum keyword
          ??? -- column defined by expressions
          6 Using the with check option Clause
          ? 1) you can ensure that dml operatons performed on the view stay within the domain of the

          view by using the with check option clause.
          ? creaate view test1
          ? as
          ? select * from emp where qty>10;
          ? with check option;
          ? update testview1 set qty=10
          ? where ster_id=6830;
          ? --when you doing the following update operation
          ? update testview1 set qty=5 where id=10;
          ? -- an error will report
          ? --you violate the where clause
          ? 2)Any attempt to change the department number for any row in the view fails because it

          violates the with check option constraint
          ?? create or replace view empvu20
          ?? as
          ?? select * where department_id=20
          ?? with check option constriant empvu20_ck;
          7 Denying DML Operations
          ? 1 You can ensure that no dml operations occur by adding the with read only option to your

          view definition.
          ? 2)Any attempt to a DML on any row in the view resuls in an oralce server error.
          8 remove veiw
          ? drop view_name
          9 inline view
          ? 1) an inline view is a subquery with an alias that you can use within a sql statement.
          ? 2) a named subquery in the from clause of the main query is an exqmple of an inline view
          ? 3) an inline view is not a schema object.
          10 Top-N Analysis
          ?1)Top_N querise ask for the n largest or smallest values of a column.
          ?2)Both largest values and smallest values sets considered Top-N queries
          ? select * from (select ster_id,qty from sales);
          ?example
          ? To display the top three earner names and salaries from the employees
          ? select rownum as rank,last_name,salary
          ? from (select last_anme,slary from employee
          ??????? order by slary desc)
          ? where rownum<=3;
          ?

          posted @ 2006-09-27 18:30 康文 閱讀(271) | 評論 (0)編輯 收藏

          使用復合變量.

          1 pl/sql 集合 處理單列多行數據庫,使用的類型為標量類型
          ?1) 索引表
          ? type ename_table_type is table of emp.ename%type
          ??? index by binary_integer;
          ? ename_table ename_table_type;
          ? begin
          ??? select ename into ename_table(-1) from emp
          ????? where empno=&no;
          ??? dbms_output.put_line('雇員名:'||ename_table(-1));
          ? end;
          ?
          ?? set serveroutput no
          ?? declare
          ???? type area_table_type is table of number
          ??????? index by varchar2(10);
          ???? rea_table area_table_type;
          ??? begin
          ??????? area_table('beijing'):=1;
          ??????? area_table('shanghai'):=2;
          ??????? area_table('guangzhou'):=3;
          ??????? dbms_output.put_line(area_table.first);
          ??????? dbms_output.put_line(area_table.last);
          ??? end;
          ???? 2) 嵌套表
          ????? 索引表類型不能作為累得數據類型使用,但是嵌套表可以作為表類的數據類型使用。
          當使用嵌套表元素時,必須先用其構造方法初始化其嵌套表:
          ?????? a? 在pl/sql 塊中使用嵌套表
          ??????? declare
          ????????? type ename_table_type is table of emp.ename%type;
          ????????? ename_table ename_table_type;
          ??????? begin
          ?????????? ename_table:=eanme_table_type('2','2','3');
          ?????????? select ename into ename table(2) from emp where empno=&no;
          ?????????? dbms_ouput.put_line(ename_table(2));
          ??????? end;
          ????? b 在表中使用嵌套表
          ??????? create type phone_type is table of varchar2(20);
          ??????? create table employee(
          ????????? id number (4),name varchar2(10),sal number(6,2),
          ????????? phone phone_type
          ??????? )nested table phone store as phone_table;
          ?????? -- 為嵌套表插入數據
          ??????? insert into employee values(2,'scott',200,phone_type('2222','333333'));
          ?????? --檢索嵌套表累得數據
          ??????? set erveroutput on
          ??????? declare
          ????????? phone_table phone_type;
          ??????? begin
          ????????? select phone into phone_table
          ????????? from employee where id=1;
          ????????? for i in 1..phone_table.count loop
          ??????????? dbms_output.put_line(phone_table(i));
          ????????? end loop;
          ??????? end;
          ?????? -- 更新嵌套表列的數據
          ???????? delcare
          ??????????? phone_table phone_type:=('44444','555555');
          ???????? begin
          ??????????? update employee set phone=phone_table
          ??????????? where id=1;
          ???????? end;
          ??? 3) 變長數組
          ????? 在使用varray 時必須指定最大個數,和數據類型,在使用其元素時必須進行初始化
          ????? type ename_table_type is varray(20) of emp.ename%type;
          ????? ename_table ename_table_type:=ename_table_type('1','2');
          ?????
          ????? -- 在快中使用varray
          ????? declare
          ???????? type ename_table_type is varray(20) of emp.ename%type;
          ???????? ename_table ename_table_type:=ename_table_type('mary');
          ???????? begin
          ??????????? select ename into ename_table(1) form emp
          ?????????????? where empno=$no;
          ????????? end;
          ????? --在表列中使用varray
          ?????? create type phone type is varray(20) of varchar2(20);
          ?????? create table employee(
          ???????? id number(4),name varchar2(10),
          ???????? sal number(6,2),phone phone_type);
          ??????
          ???? 3)記錄表
          ????? 記錄表結合了記錄和集合的優點
          ??????? declare
          ????????? type emp_table_type is table of emp%rowtype
          ????????? index by binary_integer;
          ??????? emp_table emp_table_type;
          ??????? begin
          ????????? select * from into emp_table(1) from emp
          ????????? where empno=&no;
          ????????? dbms_output.put_line(emp_table(1).ename);
          ??????? end;
          ????? 4)多維集合
          ?????? 1 多級varray
          ?????? declare
          ??????? --define 一維集合
          ????????? type al_array_type is varray(10) of int;
          ??????? --定義二維集合
          ????????? type nal_varray_type is varray(10) of a1_varray_type;
          ??????? --初始化二維集合
          ????????? nvl nal_varray_type:=nal_varray_type(
          ??????????? a1_varray_type(1,2),
          ??????????? a1_varray_type(2,3)
          ????????? )
          ???????? beign
          ?????????? for i in 1..nal_varray_type.count loop
          ????????????? for j in 1..a1_array_type.count loop
          ??????????????? dbms_out.putline(nvl(i)(j));
          ????????????? end loop;
          ?????????? end loop;
          ??????? end;
          ?????? 2 使用多級嵌套表
          ??????? table a1_table_type is table of int;
          ??????? table nvl_table_type is table of a1_table_type;
          ??????? nvl nvl_table_type:=nvl_table_type(
          ????????? a1_table_type(1,2),
          ????????? a1_table_type(2,3)
          ??????? );
          2 集合方法
          ? 1) exist
          ?? if ename_table.exists(1) then
          ??? ename_table(1):='scott';
          ?? 2) count 返回當前集合變量中的元素總個數
          ??? ename_table.count
          ?? 3) limit 返回集合元素的最大個數? 只有varray 有
          ?? 4)first and last
          ?????? ename_table.first
          ?????? ename_table.last
          ?? 5) prior 和next
          ??? ename_table.prior(5); --返回元素5的前一個
          ??? ename_table.next(5);? --? 后一個
          ?? 6) extend
          ??? 使用于varray 和 嵌套表。
          ??? extend add a null value
          ??? extend (n) add n null value
          ??? extend (n,i)add n i value
          ??? declare
          ????? type ename_table_type is varray(20) of varchar2(20);
          ????? ename_table ename_table_type;
          ??? begin
          ????? ename_table:=ename_table_type('mary');
          ????? ename_table.extend(5,1);
          ????? dbms_output.put_line(ename_table.count);
          ??? end;
          ?? 7) trim
          ?? trim remove one element from the tail of the collection.
          ?? trim(n) remove n element from the tail of the colleciton.
          ?? 8)delete
          ??? delete: delete all the elements
          ??? delete(n) :delete the nth elements
          ??? delete(m,n): delete the elements from m to n
          3 集合賦值
          ? 1)將一個集合的數據賦值給另一個集合.clear the destination collectins and set the original

          collection
          ?? delcare
          ??? type name_varray_type is varray(4) of varchar2(10);
          ??? name_array1 name_varray_type;
          ??? name_array2 name_varray_type;
          ?? begin
          ???? name_array1:=name_varray_type('scott','smith');
          ???? name_array2:=name_array_type('a','b','c');
          ???? name_array1:=name_array2;??
          ?? end;
          ??
          ?
          ? type name_array1_type is varray(4) of varchar2(10);
          ? type name_array2_type is varray(4) of varchar2(10);
          ? name_array1 name_array1_type;
          ? name_array2 name_array2_type;
          ? 具有相同的數據類型,單具有不同的集合類型不能構賦值
          ? 2) 給集合賦城null 值
          ??? 可以使用delete 或 trim
          ??? 也可以使用 空集合賦給目表集合
          ??? type name_varray_type is varray(4) of varchar2(10);
          ??? name_array name_varray_type;
          ??? name_empty name_varray_type;
          ???
          ??? name_array:=name_varray_type('1','2');
          ??? name_array:=name_empty;
          ? 3) 使用集合操作賦和比較集合都是10g 的內容,p176 先略過。
          4 批量綁定
          ? 執行單詞sql 操作能傳遞所有集合元素的數據。
          ? 1 forall 語句
          ? 用于insert update 和delete操作。在oracle9i 中forall 語句必須具有連續的元素
          ??? 1) using forall on insert
          ???? declare
          ??????? type id_table_type is table of number(6)
          ??????? index by binary_integer;
          ??????? type name_table_type is table of varchar2(2)
          ??????? index by binary integer;
          ??????? id_table id_table_type;
          ??????? name_table name_table_type;
          ????? begin
          ???????? for i in 1..10 loop
          ?????????? id_table(i):=i;
          ?????????? name_table(i):='Name'||to_char(i);
          ???????? end loop;
          ???????? forall i in 1..id_table.count
          ?????????? insert into demo demo values(id_table(i),name_table(i));
          ????? end;
          ???? 2)using forall on using update
          ?????? forall i in 1..id_table.count
          ?????????? upate demo set name:=name_table(i)
          ????????????? where id:=id_table(i);
          ???? 3)using forall on using delete
          ??????? forall i in 1..id_table.count
          ??????????? delete from demo where id:=id_table(i);
          ???? 4) using forall on part of the collection
          ??????? for i in1..10 loop
          ????????? id_table(i):=i;
          ????????? name_table(i):="name"||to_char(i);
          ??????? end loop;
          ??????? forall i in 8..10 l
          ?????????? insert into demo values(id_table(i),name_table(i));
          ?? 2 bulk collect
          ???? is fit for select into ,fetch into and dml clause
          ???? 1) using bulk collect
          ????? declares??
          ??????? type emp_table_type is table of emp%rowtype
          ???????? index by binary_integer;
          ??????? emp_table emp_table_type;
          ????? begin
          ???????? select * bulk collect into emp_table
          ????????? from emp where deptno=&no;
          ???????? for i in 1..emp_tablee.count loop
          ??????????? dbms_output.put_line(emp_table(i).ename);
          ???????? end loop;
          ????? 2) 在dml 的返回字句使用bulk collect 字句
          ???????? declare
          ????????? type ename_table_type is table of emp.ename%type;
          ?????????? ename_table ename_table_type;
          ????????? begin
          ???????????? deletee from emp where deptno=&no
          ???????????? returning ename bulk_collect into ename_table;
          ????????? for i in 1..ename_table.count loop
          ??????????? dbms_output.put(ename_table(i));
          ????????? end loop;
          ??????? end;
          ????????? end;
          ????? end;

          posted @ 2006-09-27 15:46 康文 閱讀(202) | 評論 (0)編輯 收藏

          including constraint

          1 What are Constrains
          ? 1) Constrains enforce on the table level
          ? 2) Constrains the deletion of a table if there are dependencies
          2 Constrain Guidelines
          ? 1) Name a constraint or the oracle generate a name by the sys_cn format
          ? 2) Create a constraint either
          ???? --At the same time as the table is created.or
          ???? --After the table has been created
          ? 3)Define a constraint at the column or table level
          ? 4)view constraint in the data dictionary
          3 Crete a constraint
          ? create table test2
          ? (id int not null,-- column level
          ?? lname varchar(20),
          ?? fname varchar(20),
          ?? constraint uk_test2_1 unique(lname,fname))--table level
          4 The not null Constraint
          ? create table employees(
          ?? employee_id number(6),
          ?? last_name?? varchar2(25) not null? --system named
          ?? hire_date?? DATE
          ?????????????? constraint emp_hire_date not null --User named
          5Foreign key
          ? create table test3
          ? (rid int,
          ?? name varchar(30),
          ?? constraint fk_test3_1 foreign key(rid) reference test2(id));
          ? froeign key constraint keywords
          ??? foreign key :Define the column in thee child table at the table constrain level.
          ??? references? :Identifies the table and column in the parent table.
          ??? on delete cascade: Delete the dependent rows in the child table when a row in the????

          parent table is deleted
          ??? on delete set null:Convert the dependent foreign key values to null when a row in the
          ??? parent table is deleted.
          ??
          ??? --parent table referenced table
          ??? --child table refernce other table
          6 The check Constraint
          ? Define a condition that each row must be satify
          ? alter table test3
          ? add constrain ch_test3 check(name like 's%')
          7 Dropping a Constraint
          ? 1) Remove the manager constraint form the employee table
          ?? alter table test3
          ?? drop constriant test3_manager_fk
          ? 2) Remove the primary key constraint on the departments table and drop the associated
          ?? foreign key constraint on the employees.department_id column
          ?? alter table departments
          ?? drop primary key cascade
          8 Disabling and enable Constraints
          ? 1)Execute the disable clause of the alter table statment to deactive an integrity

          constraint
          ? 2)Apply the cascade option to disable dependent integrity constrints
          ? alter table employees
          ? disable constraint emp_emp_id_pl cascade
          ? 3) enabling Constraints
          ? .Active an integrity constraint currently disabled in the table definition by using the

          enable clause.
          ?? alter table employees
          ?? enable constraint emp_emp_id_pk;
          ? a unique? or a primary? index is automatically created if you enable a unique key or a

          primary key constraint?
          ?8 View Constraints
          ? select constraint_name,constriant_type,serch_condition
          ? from user_constraints
          ? where table_name='employees'
          ?9 view the columns associated with constraints
          ?select constraint_name,column_name
          ?from user_cons_columns
          ?where table_name='employees'

          posted @ 2006-09-26 14:44 康文 閱讀(224) | 評論 (0)編輯 收藏

          OpenSessionInViewFilter解決Web應用程序的問題 轉自:Potain 的BLOG

          OpenSessionInView

          Created by potian. Last edited by admin 61 days ago. Viewed 181 times.
          [edit] [attach]
          Hibernate的Lazy初始化1:n關系時,你必須保證是在同一個Session內部使用這個關系集合,不然Hiernate將拋出例外。

          另外,你不愿意你的DAO測試代碼每次都打開關系Session,因此,我們一般會采用OpenSessionInView模式。

          OpenSessionInViewFilter解決Web應用程序的問題

          如果程序是在正常的Web程序中運行,那么Spring的OpenSessionInViewFilter能夠解決問題,它:

          protected void doFilterInternal(HttpServletRequest request, 
                       HttpServletResponse response,
          	     FilterChain filterChain) throws ServletException, IOException {
          	SessionFactory sessionFactory = lookupSessionFactory();
          	logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");
          	Session session = getSession(sessionFactory);
          	TransactionSynchronizationManager.bindResource(sessionFactory, 
                       new SessionHolder(session));
          	try {
          		filterChain.doFilter(request, response);
          	}
          	finally {
          		TransactionSynchronizationManager.unbindResource(sessionFactory);
          		logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
          		closeSession(session, sessionFactory);
          	}
          }
          可以看到,這個Filter在request開始之前,把sessionFactory綁定到TransactionSynchronizationManager,和這個SessionHolder相關。這個意味著所有request執行過程中將使用這個session。而在請求結束后,將和這個sessionFactory對應的session解綁,并且關閉Session。

          為什么綁定以后,就可以防止每次不會新開一個Session呢?看看HibernateDaoSupport的情況:

          publicfinal void setSessionFactory(SessionFactory sessionFactory) {
              this.hibernateTemplate = new HibernateTemplate(sessionFactory);
            }
           protectedfinal HibernateTemplate getHibernateTemplate() {
            return hibernateTemplate;
           }

          我們的DAO將使用這個template進行操作:

          publicabstract class BaseHibernateObjectDao
          	extends HibernateDaoSupport
          	implements BaseObjectDao {

          protected BaseEntityObject getByClassId(finallong id) { BaseEntityObject obj = (BaseEntityObject) getHibernateTemplate() .execute(new HibernateCallback() {

          publicObject doInHibernate(Session session) throws HibernateException { return session.get(getPersistentClass(), newLong(id)); }

          }); return obj; }

          public void save(BaseEntityObject entity) { getHibernateTemplate().saveOrUpdate(entity); }

          public void remove(BaseEntityObject entity) { try {

          getHibernateTemplate().delete(entity); } catch (Exception e) { thrownew FlexEnterpriseDataAccessException(e); } }

          public void refresh(final BaseEntityObject entity) { getHibernateTemplate().execute(new HibernateCallback() {

          publicObject doInHibernate(Session session) throws HibernateException { session.refresh(entity); returnnull; }

          }); }

          public void replicate(finalObject entity) { getHibernateTemplate().execute(new HibernateCallback() {

          publicObject doInHibernate(Session session) throws HibernateException { session.replicate(entity, ReplicationMode.OVERWRITE); returnnull; }

          }); }

          而HibernateTemplate試圖每次在execute之前去獲得Session,執行完就力爭關閉Session
          publicObject execute(HibernateCallback action) throws DataAccessException {
          	Session session = (!this.allowCreate ?
          		SessionFactoryUtils.getSession(getSessionFactory(), 
                            false) :
          		SessionFactoryUtils.getSession(getSessionFactory(),
                            getEntityInterceptor(),
                            getJdbcExceptionTranslator()));
          	boolean existingTransaction =  
                    TransactionSynchronizationManager.hasResource(getSessionFactory());
          	if (!existingTransaction && getFlushMode() == FLUSH_NEVER) {
          		session.setFlushMode(FlushMode.NEVER);
          	}
          	try {
          		Object result = action.doInHibernate(session);
          		flushIfNecessary(session, existingTransaction);
          		return result;
          	}
          	catch (HibernateException ex) {
          		throw convertHibernateAccessException(ex);
          	}
          	catch (SQLException ex) {
          		throw convertJdbcAccessException(ex);
          	}
          	catch (RuntimeException ex) {
          		// callback code threw application exception
          		throw ex;
          	}
          	finally {
          		SessionFactoryUtils.closeSessionIfNecessary(
                              session, getSessionFactory());
          	}
          }
          而這個SessionFactoryUtils能否得到當前的session以及closeSessionIfNecessary是否真正關閉session,端取決于這個session是否用sessionHolder和這個sessionFactory在我們最開始提到的TransactionSynchronizationManager綁定。
          publicstatic void closeSessionIfNecessary(Session session, 
              SessionFactory sessionFactory)   
              throws CleanupFailureDataAccessException {
          	if (session == null || 
          	   TransactionSynchronizationManager.hasResource(sessionFactory)) {
          		return;
          	}
          	logger.debug("Closing Hibernate session");
          	try {
          		session.close();
          	}
          	catch (JDBCException ex) {
          		// SQLException underneath
          		thrownew CleanupFailureDataAccessException(
          		"Cannot close Hibernate session", ex.getSQLException());
          	}
          	catch (HibernateException ex) {
          		thrownew CleanupFailureDataAccessException(
          		"Cannot close Hibernate session", ex);
          	}
          }

          HibernateInterceptor和OpenSessionInViewInterceptor的問題

          使用同樣的方法,這兩個Interceptor可以用來解決問題。但是關鍵的不同之處在于,它們的力度只能定義在DAO或業務方法上,而不是在我們的Test方法上,除非我們把它們應用到TestCase的方法上,但你不大可能為TestCase去定義一個接口,然后把Interceptor應用到這個接口的某些方法上。直接使用HibernateTransactionManager也是一樣的。因此,如果我們有這樣的測試:

          Category parentCategory  = new Category ();
          	parentCategory.setName("parent");
          	dao.save(parentCategory);

          Category childCategory = new Category(); childCategory.setName("child");

          parentCategory.addChild(childCategory); dao.save(childCategory);

          Category savedParent = dao.getCategory("parent"); Category savedChild = (Category ) savedParent.getChildren().get(0); assertEquals(savedChild, childCategory);

          將意味著兩件事情:
          • 每次DAO執行都會啟動一個session和關閉一個session
          • 如果我們定義了一個lazy的關系,那么最后的Category savedChild = (Category ) savedParent.getChildren().get(0);將會讓hibernate報錯。

          解決方案

          一種方法是對TestCase應用Interceptor或者TransactionManager,但這個恐怕會造成很多麻煩。除非是使用增強方式的AOP.我前期采用這種方法(Aspectwerkz),在Eclipse里面也跑得含好。

          另一種方法是在TestCase的setup和teardown里面實現和Filter完全一樣的處理,其他的TestCase都從這個TestCase繼承,這種方法是我目前所使用的。

          Jolestar補充:openSessionInView的配置方法:

          ?? <filter>
          ? ? ? ? <filter-name>opensession</filter-name>
          ? ? ? ? <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
          ? ? ? ? <init-param>
          ? ? ? ? ? ? <param-name>singleSession</param-name>
          ? ? ? ? ? ? <param-value>false</param-value>
          ? ? ? ? </init-param>
          ? ? </filter>

          posted @ 2006-09-26 11:01 康文 閱讀(553) | 評論 (0)編輯 收藏

          creating and manipulation table

          1 Table in the Oracle Database
          1) User Tables:
          ? a Are a collection of tables created and maintained by the user
          ? b Contain user information
          ?2) Data Dictionary
          ? a is a collection of table created and maintained by the Oracle Server
          ? b Contain database information
          2 Querying the Data Dictionary
          ?1)see the names of the table owned by the user
          ?? select table_name from user_tables;
          ?2) view distinct object types ownered by the user
          ?? select distinct object_type from user_object;
          ?3) view tables ,view ,synonyms and sequences owned by the user
          ?? select * from user_catalog
          3 Creating a Table by Ussing a Subquery Syntax
          ?create table tt3
          ?as
          ?select * from authors
          4 Teh alter table Statement
          ?1) Add a new column
          ? alter table tt2
          ? add(fname varchar2(20) default 'unkonown',
          ????? address varchar2(30) null);
          ?2)Modigying a Column's data type size and default value
          ? alter table dept80
          ? modigy (last_name varchr2(30))
          ? A change to thee default value affects onlly subsequent insertion to the table
          ? 3) drop a column
          ? alter table dept80
          ? drop column job_id;
          ? The set unseed Option
          ?? a you use the set unused optoin to mark one or more columns as unused
          ?? b you use the drop unused colimns options to remove the columns that are marked as
          ?? as unused
          ?? alter table tt2
          ?? set unused colun fnamel;
          ?? alter table table
          ?? drop unused columns
          5 Dropping a Table
          ?1) All data and structure in the table is deleted
          ?2) Any pending transaction are committed
          ?3) All indexes are dropped
          ?4) You cannot roll back the drop table statement
          6 Changing the Name of an Object
          ? rename dept to detail_dept;
          ? you must be the owner of the object
          7 Truncate a Table
          ? Remove all rows from the table
          ? release the storage space used by that table
          ? you cannot rollback row when using truncate
          ? alternatly ,you can remove row by using delete statement

          posted @ 2006-09-25 17:59 康文 閱讀(202) | 評論 (0)編輯 收藏

          Data manipulation

          1 Data Manipulation Language
          ? 1) A DML statement is executed when you:
          ???? add new rows to a table
          ???? modify existing row in a table
          ???? remove existing rows from a table
          ? 2) A transaction consist a collection dml statements form a logic unit of work
          2 Using Explicit Default Values
          ?1) default with insert
          ?insert into departments
          ?values(200,'ddd',default)
          ?2) default with update
          ?update departments
          ?set manager_id=default where department_id=10
          3 The Merge Statement
          ?1)Provide the ability to conditionaly update or insert data into database
          ?2)Perform a update if the row exists and an insert if it is a new row
          ?? a Avoid update separatly
          ?? b increase performance and ease of use
          ?? c is useful in data warehousing application
          ?? example
          ??? merge into copy_emp c
          ??? using employees e
          ??? on (c.employee_id=e.employee_id)
          ??? when mathched then
          ??? update set
          ????? c.first_name=e.first_name
          ????? c.last_name=e.last_name
          ????? ..............
          ????? c.department_id=e.department_id
          ??? when not matched then
          ??? insert values(e.employeeid,e.first_name,......e.department_id);
          4 Database Transactions
          ?1)Begin when the first dml statement is executed
          ?2)end with one of the following events
          ?? a a commit or rollback statement is issued;
          ?? b a ddl or dcl statement execute (commit automatically)
          ?? c the user exist isqllplus
          ?? d the system crashes
          ?3) advantage of commit and rollback statemnt
          ?? With commit and rollback statement ,you can
          ??? a ensure data consistence
          ??? b Preview data change before making change permant
          ??? c group logic relate operatons
          5 State of The Data Before commit or rollback
          ?1) the previous state of the data can be recovered
          ?2) The current user can review the result of the dml operation by using the select statment
          ?3) other user can not view the result of the dml
          ?4) the affected was locked ,other user cannot change the data within the affecteed row
          6 Read Consistency
          ?1) Read consistency guarantees a consistent view of the data at all times
          ?2) Changes made by one user do not confilict with changes made by another user
          ?3) Read consistency ensures that on the same data
          ??? a Readers do not wait for writers
          ??? b Writers do not wait for readers
          7Locking
          ? 1) Prevent destructive interaction between concurrent transactions
          ? 2) Reqire no user action
          ? 3) Automatically use the lowest level of restrictiveness
          ? 4) Are held for the duration of the transaction
          ? 5) Are of two types:explicit locking an implicit locking
          8 Implicit Locking
          ? 1)Two lock modes
          ??? a Exclusive :Locks out other users
          ??? b Share: Allows other users to accesss
          ? 2)High level of data concurrency
          ??? a DML:Table share,row exclusive
          ??? b Queries: No locks required
          ??? c DDL:Protects object definitions
          ? 3)Locks held until commit or rollback

          posted @ 2006-09-25 16:25 康文 閱讀(240) | 評論 (0)編輯 收藏

          sequence 的用法

          剛剛用sequence ,又忘了,呵呵,從網上找了一篇文章,寫的不錯,copy 在這里
          1、Create?Sequence?
          你首先要有CREATE?SEQUENCE或者CREATE?ANY?SEQUENCE權限,?
          CREATE?SEQUENCE?emp_sequence?
          ????INCREMENT?BY?1??--?每次加幾個?
          ????START?WITH?1????--?從1開始計數?
          ????NOMAXVALUE??????--?不設置最大值?
          ????NOCYCLE?????????--?一直累加,不循環?
          ????CACHE?10;?

          一旦定義了emp_sequence,你就可以用CURRVAL,NEXTVAL?
          ?CURRVAL=返回?sequence的當前值?
          ?NEXTVAL=增加sequence的值,然后返回?sequence?值?
          比如:?
          ??emp_sequence.CURRVAL?
          ??emp_sequence.NEXTVAL?

          可以使用sequence的地方:?
          -?不包含子查詢、snapshot、VIEW的?SELECT?語句?
          -?INSERT語句的子查詢中?
          -?NSERT語句的VALUES中?
          -?UPDATE?的?SET中???

          可以看如下例子:?
          INSERT?INTO?emp?VALUES??
          (empseq.nextval,?'LEWIS',?'CLERK',7902,?SYSDATE,?1200,?NULL,?20);?

          SELECT?empseq.currval?????FROM?DUAL;?

          但是要注意的是:?
          -?第一次NEXTVAL返回的是初始值;隨后的NEXTVAL會自動增加你定義的INCREMENT?BY值,然后返回增加后的值。CURRVAL?總是返回當前SEQUENCE的值,但是在第一次NEXTVAL初始化之后才能使用CURRVAL,否則會出錯。一次NEXTVAL會增加一次SEQUENCE的值,所以如果你在同一個語句里面使用多個NEXTVAL,其值就是不一樣的。明白??

          -?如果指定CACHE值,ORACLE就可以預先在內存里面放置一些sequence,這樣存取的快些。cache里面的取完后,oracle自動再取一組到cache。?使用cache或許會跳號,?比如數據庫突然不正常down掉(shutdown?abort),cache中的sequence就會丟失.?所以可以在create?sequence的時候用nocache防止這種情況。?

          2、Alter?Sequence?
          你或者是該sequence的owner,或者有ALTER?ANY?SEQUENCE?權限才能改動sequence.?可以alter除start至以外的所有sequence參數.如果想要改變start值,必須?drop??sequence?再?re-create?.?
          Alter?sequence?的例子?
          ALTER?SEQUENCE?emp_sequence?
          ????INCREMENT?BY?10?
          ????MAXVALUE?10000?
          ????CYCLE????--?到10000后從頭開始?
          ????NOCACHE?;?


          影響Sequence的初始化參數:?
          SEQUENCE_CACHE_ENTRIES?=設置能同時被cache的sequence數目。??

          可以很簡單的Drop?Sequence?
          DROP?SEQUENCE?order_seq;?

          posted @ 2006-09-24 16:08 康文 閱讀(717) | 評論 (0)編輯 收藏

          subqueries

          1 Guidelines for Using Subqueries
          ?a Enclose subqueries in parenttheses
          ?b placce subqueries on the right side of the comparision condition
          ?c the order by clause in the subquery is not needed
          ?d using single-row operators with single-row subqueries and use multiple -row operator with multiple-row subqueries .
          ? single-row subqueries can work as a expression,and muitiple-row subqueries can only be used with in all any ,i will talk it later
          ? select last_name where job_idd=(select job_id
          ????????????????????????????????? from employees
          ????????????????????????????????? where imployee_id=141)
          2 The HAVING CLause with Subqueries
          ?a The Oracle server execute subqueries first
          ?b The Oracle return result into the HAVING clause of the main query
          ? select department_id,min(salary)
          ? from employee
          ? group by department_id
          ? having min(salary)>
          ???????????????????? (select min(salary)
          ????????????????????? from employees
          ????????????????????? where department_id=50);
          3 Multiple-Row Subqueries
          ? a Return? more than one row
          ? Using mutiple-row comparsion operator
          ? select employee_id
          ? from employees
          ? where salary<any
          ????????????????? (select salary
          ?????????????????? from employees
          ?????????????????? where job_id='ddd')

          ? select employee_id
          ? from employees
          ? where salary<all
          ????????????????? (select salary
          ?????????????????? from employees
          ?????????????????? where job_id='ddd')
          ?? select emp.last_name
          ?? from employees emp
          ?? where emp.employee_id not in
          ?????????????????????????????? (select mgr.manager_id
          ??????????????????????????????? from employees mgr)

          posted @ 2006-09-22 16:25 康文 閱讀(255) | 評論 (0)編輯 收藏

          jointable

          1 Jioning Tables Using Oracle Syntax
          Using a join to query data form more than one table
          select table1.column,table2,column
          from table1,table2
          where table1.column1=table2.column2 .
          2 outjoin
          ?1)You use an outer join to also see rows that do not meet the join condition
          ?2)The Outer join operator is the plus sign(+)
          ?? a left join
          ???? select tabl1.column,table2,column
          ???? from table1,table2
          ???? where table1.column(+)=table2.column
          ? b? right join
          ???? select table1.column,table2.column
          ???? from table1,table2
          ???? wheretable1.coulmn=table2.column(+)
          ? 3) self join
          ???? select worker.last_name||'works for'||manager.last_name
          ???? from? employees owrker,employees manager
          ???? where worker.manager_id=manager.employee_id;
          ?
          3 Joining Tables Using SQL:1999 Syntax
          ? Use a join to query data from more than one table
          ? 1) Creationg Cross Joins
          ?? a The cross join clause produces thee cross product of two tables
          ?? b This is the same as Cartesian product between the two tables
          ?? select last_name,department_name
          ?? from employees
          ?? ccross join departments
          ? 2) Creating Natual Joins
          ?? a The Natual join clause is bassed on all columns in the two tables that have the same name
          ?? b it select rows from the two tables that have the equal values in all matched columns
          ?? c if the columns having the same name and have the different data types in an error is returned.
          ?? select department_id,department_name,location_id,city
          ?? from departments
          ?? natual join locations
          ?3) using clause
          ?? select e.employee_id,e.last_name
          ?? from employees e join departments d
          ?? using (department_id);
          ?4) Creating joins with thee on clause
          ? a The join condition for thee natual join is basically an equaljoin of all column with the same name.
          ? b To specify arbitrary condition or specify columns to join, the on clause is userd
          ? c The join condition is separated from other search conditions
          ? d The on claus make code easy to understand.
          ? select e.employee_id,e.last_name,e.department_id,
          ? from employees e join departments d
          ? on (e.department_id=d.department_id);
          ?
          ? from employe
          ? join departments d
          ? on d.department_id=e.department_id
          ? join locations l
          ? on d.location_id=l.location_id
          ?5) INNER Versus OuTER Joins
          ? a In SQL:1999,the join of two tables returning only matched rows is an inner join
          ?6) FULL OUTER JOIN
          ? select e.last_name,e,department_id,d.department_name
          ? from employees e
          ? full outer join departments d
          ? on (e.department_id=d.department_id);
          ?

          posted @ 2006-09-22 14:55 康文 閱讀(366) | 評論 (0)編輯 收藏

          sql function

          1 "'
          2 ||
          3 isql*plus? http://127.0.00.1/isqlplus
          4 desc author
          5 initcap('SQL Course')
          ? INSERT('JellwWord','W')? 6
          ?? LPAD (salary,10,'*')? *****24000
          ?? RPAD (salary,10,'*')? 24000*****
          ?? TRIM ('H' from 'HolloWorld') olloWord
          ?? substr('helloword',1,5)? hello
          ?? substr('helloword',-1,5) oword
          6? Number Functions
          ?? round(45.926,2)?? 45.93
          ?? round(45.926,-2) 0
          ?? round(55.926,-2) 100
          ?? trunc(45.926,2)?? 45.92
          ?? mod(1600,300)? 100
          7 data function
          ?? systdate
          ?? (sysdate-hire_date)/7 as weeks
          ?? months_between? number of months between two dates
          ?? months_between ('01-sep-95','11,jan-94')? 19.6774194
          ?? add_months????? add calendar months to date
          ?? add_months('11-JAN-94',6)? '11-JUL-94'
          ?? next_day??????? next day of the date specified
          ?? next_day('01-SEP-95','FRIDAY') '08-SEP-95'
          ?? last_day??????? last day of the month
          ?? last_day('01-feb-95')? '28-feb-95'
          ?? round?????????? round date
          ?? assume sysdate='25-jul-95'
          ?? round(sysdate,'month') 01-aug-95
          ?? round(sysdate,'year')? 01-JAN-96
          ?? trunc?????????? truncate date
          ?? trunc(sysdate,'month') 01-Jul-95
          ?? trunc(sysdate,'month') 01-JAN-95
          8? Conversion Functions?
          ? 1) implicit data typ conversion
          ?? varchar2 or char? ---number
          ?? varchar2 or char? ---date
          ?? numbeer?????????? ---varchar2
          ?? date????????????? ---varchar2
          ? 2) to_char(date,'format')
          ? format:
          ??? YYYY Full year in numbers
          ??? YEAR Year spelled out
          ??? MM?? Two-digit value for month
          ??? MONTH Full name of the month
          ??? MON? THree-letter abbreviation of the month
          ??? DY?? Three-letter abbreviation of the day of the week
          ??? DAY? Full name of the day of hte week
          ??? DD?? Numberic day of the month
          ??? HH24:MI:SS AM? 15:45:32:PM
          ??? DD "of"? MONTH 12 of october
          ? 3) to_char function with number?
          ?? TO_CAHR(number,'format_model')
          ?? These are some of the format elements you can use with the to_char function to display number as a character.
          ??? 9 Reqresents a number
          ??? 0 Forces a zero to be displayed
          ??? $ Places a flationg dollar sign
          ??? L Uses the floating local currency symbol
          ??? . Prints a decimal point
          ??? , Print a thousand director
          ? select to_char(qtym,"$999.99")
          ? 4) Using t_number and to _date functions
          ?? a converting a character string to a number format using to_number function
          ?? to_number(char,"format")l
          ?? b converting a character string to a date format
          ?? to_date(char,"format")
          5 Nesting Functions
          .Single-row function can be nested to many level
          .Nested function can be evaluated from deepest level
          6General Function
          These function work with any data type and pertain to using nulls
          nvl(expr1,expr2);
          nvl2(expr1,expr2,expr3)
          nullif(expr1,expr2)
          coalesce(expr1,expr2,,,,exprn)
          ?1) nvl function
          ?convert a null to an actual function
          ?a Data type can be used are data character and number
          ?b Data types must match??????????????????????????????
          ?(set wrap off
          ? set line 1000
          ?)
          ?2)Using the COALESCE Function
          ?a The advantage of the coalesce function over nal function is that coalesce function can take multiple alternative value
          ?b If the first value is not null, it return that expression,otherwise,it does a coalesce of remaining expressions
          6 Conditional Expressions
          ?a Provide the use of if-then-else logic
          ?b use two methods: case expression decode function
          ? select last_name,job_id,salary,
          ???????? case job_id when 'it' then 1*salary
          ????????????????????? when 'manager' then 1.2*salary
          ???????? else salary end;
          ? from employee.

          ? select last_namek,job_id,salary,
          ???????? decode(job_id,'it' ,1*salary,
          ??????????????????????? 'manager',1.2*salary,
          ??????????????? salary)
          ?? from employees
          ??

          posted @ 2006-09-22 11:50 康文 閱讀(366) | 評論 (0)編輯 收藏

          Aggregating Datas Using Group Functionbs.

          1 What Are Group Functions
          Group functions operatee on sets of rows to give one result per group
          ?1)agg,count,max,min,stddev,sum,variance
          ?select avg(salary),max(salary),min(salary),sum(salary)
          ?from employees
          ?where job_id like '%REP%'

          ?select count(*) from
          ?select count(address) from authors
          ?count the valid count of the address (exclude the null value)
          ?2) Using theDISTINCT Keyword
          ? count(distinct expr) return thee number of the distinct non-null value of the expr
          ? select count(distincee department_id) from employees
          ?3)Group functions and null values
          ? group functions ignore null values in the clumn
          ?4) Using thee NVL Function with Group Functions
          ? The nul function force group funtion to include null values
          ? select avg(nvl(commission_pct,0)) from employees
          2 Creating Groups of Data
          ? 1)
          ? a Divide rows in a table into smaller groups by using the group by clause
          ? b All coulmns in the select list that are not in group function must be in the group by clause
          ? select department_id,avg(salary)
          ? from employees
          ? group by department_id;
          ? 2) Grouping by More Than One Column
          ? 3) Ilegal Queries Using Group Functions
          ?? a You cannot use thee where clause to restrict groups
          ?? b You use thee having clause to restrict groups
          ?? c you cannot use group functions in the where clause
          ? 4)Excluding Group Resdults:The Having Clause
          ?? Use the HAVING clause to restrict groups
          ?? a Rows are grouped
          ?? b The group functions is applied
          ?? c Groups matcching the Having clause are display
          ? select department_id,max(salary)
          ? from employees
          ? group by department_id
          ? having max(salary)>10000
          ?5) Nesting Group function
          ?select max(avg(salary))
          ?from employees
          ?group by department_id;

          posted @ 2006-09-22 11:49 康文 閱讀(201) | 評論 (0)編輯 收藏

          window programming --keybord.txt

          1 Keyboardd Basics
          ?1) Ignoring the Keyboard
          ?Your programm does not need to act on every keyboard message it received,Window handle many keyboard message function itself.
          ?2)Who's Got thefocus
          ? Though the keyboard is shared by all the window in the application ,The DispatchMessage send the message to the window procedure associated the window which message is intended.
          ? The window that receives a particular keyboard event is the window has the input foucs.
          ? Sometime no window has input foucs,this is the case if all your programs have been minmized,window continue send keyboard to the active window ,but it is send in the deffert form from sending to the input foucs.
          ? A window procedure can be determine when its window has the input focus by trapping WM_SETFOCUS and WM_KILLFOCUS.
          ?3) Queues and Synchronization
          ? As the user presses and releases key on keyborad,Windows and keyboard device driver translate the hardware scan code into formatted message.Howerver the messages are not palced on the application queue right away,Instean Windows store these message in a system message queue .The System message queue is a single message maintained by windows specifically for the prelimary storage of user input from keyboard and the mouse. Window will take the next message from the system message queue and place it on the application message queue only when a window application has finished proecssing the previous user input message.
          4) Keystorkes and Character
          ?The message that an application receives from windows about keyboard events distingush between keystrokes and characters.
          ?for instance The keysokes has only one key labbed 'A' ,and the character may be 'a' or 'ctr-a' etc.
          2 Keystroke Message
          ?1)Wirtual key Codes
          ? The virtual key code is stored in the wParam parameter of WM_KEYDOWN,WM_KEYUP,the code identifies the key being pressed or release.
          ? 2)lParam Information
          ? the wParam message parameter contain virtual key code and the lparam message parameter contains other information in understanding the keystoke.
          ? 3) Shift States
          ? iState = GetKeyState (VK_SHIFT) ;
          ? iState variable will be negative if the Shift key is donw
          ? iState = GetKeyState (VK_CAPITAL) ;
          ? 4)Using Keystroke Messages
          ???
          ? 5)
          ?? case WM_KEYDOWN:
          ???? switch (wParam)
          ???? {
          ???? case VK_HOME:
          ????????? SendMessage (hwnd, WM_VSCROLL, SB_TOP, 0) ;
          ????????? break ;

          ???? case VK_END:
          ????????? SendMessage (hwnd, WM_VSCROLL, SB_BOTTOM, 0) ;
          ????????? break ;

          ???? case VK_PRIOR:
          ????????? SendMessage (hwnd, WM_VSCROLL, SB_PAGEUP, 0) ;
          ????????? break ;
          3 Character Messages
          Message Key or Code
          WM_KEYDOWN Virtual key code for `A' (0x41)
          WM_CHAR Character code for `a' (0x61)
          WM_KEYUP Virtual key code for `A' (0x41)

          Message Key or Code
          WM_KEYDOWN Virtual key code VK_SHIFT (0x10)
          WM_KEYDOWN Virtual key code for `A' (0x41)
          WM_CHAR Character code for `A' (0x41)
          WM_KEYUP Virtual key code for `A' (0x41)
          WM_KEYUP Virtual key code VK_SHIFT (0x10)

          Key Character Code Duplicated by ANSI C? Escape
          Backspace???? 0x08 Ctrl-H??????????????? \b
          Tab?????????? 0x09 Ctrl-I??????????????? \t
          Ctrl-Enter??? 0x0A Ctrl-J??????????????? \n
          Enter???????? 0x0D Ctrl-M???????????????? \r
          Esc 0x1B Ctrl-[

          ? case WM_CHAR:
          ???? [other program lines]
          ???? switch (wParam)
          ???? {
          ???? case `\b':????????? // backspace
          ????????? [other program line
          ????????? break ;
          ???? case `\t':????????? // tab
          ????????? [other program lines]
          ????????? break ;

          ???? case `\n':????????? // linefeed
          ????????? [other program lines]
          ????????? break ;

          ???? case `\r':????????? // carriage return
          ????????? [other program lines]
          ????????? break ;

          ???? default:??????????? // character codes
          ????????? [other program lines]
          ????????? break ;
          ???? }
          ???? return 0 ;

          posted @ 2006-09-19 18:25 康文 閱讀(288) | 評論 (0)編輯 收藏

          windows programming --window and message

          1 An Architectural Overview
          ? 1)Getting a good feel for messages is an import part of learning how to write programs for windows.
          ? Windows send a message to your porgram means that Windows calls a function in your program .The parameter of this function describe the message that is being send.The function in your program is know as Window Procedure.
          ? Windows send a message to window by calling window procedure ,The window procedure do some processing based on the message and return control to Windows.
          ? More precisely , a Window? is always createdd based on a "window class".The window class identifies the window procedure that precesses messages to the windows.The use of window class allow mutiple window to be based the same window class and hence use the same window procedure.
          ? 2) Requsteriing the Window Class
          ?typedef struct
          ?{
          ???? UINT??????? style ;
          ???? WNDPROC???? lpfnWndProc ;
          ???? int???????? cbClsExtra ;
          ???? int???????? cbWndExtra ;
          ???? HINSTANCE?? hInstance ;
          ???? HICON?????? hIcon ;
          ???? HCURSOR???? hCursor ;
          ???? HBRUSH????? hbrBackground ;
          ???? LPCTSTR???? lpszMenuName ;
          ???? LPCTSTR???? lpszClassName ;
          ?}
          ?if (!RegisterClass (&wndclass))
          ?{
          ???? MessageBox (NULL, TEXT ("This program requires Windows NT!"),
          ???????????????? szAppName, MB_ICONERROR) ;
          ???? return 0 ;
          ?}
          ?2)Creating the Window
          ? Window class define the general Characteristics of the a window.If you want to create window based on the same window class,you can use CreateWindwo which allow you to specify more detail imformation about the window.
          ? hwnd = CreateWindow (szAppName,????????????????? // window class name
          ???????????????????? TEXT ("The Hello Program"), // window caption
          ???????????????????? WS_OVERLAPPEDWINDOW,??????? // window style
          ???????????????????? CW_USEDEFAULT,????????????? // initial x position
          ???????????????????? CW_USEDEFAULT,????????????? // initial y position
          ???????????????????? CW_USEDEFAULT,????????????? // initial x size
          ???????????????????? CW_USEDEFAULT,????????????? // initial y size
          ???????????????????? NULL,?????????????????????? // parent window handle
          ???????????????????? NULL,?????????????????????? // window menu handle
          ???????????????????? hInstance,????????????????? // program instance handle
          ???????????????????? NULL) ;???????????????????? // creation parameters

          ?3)Displaying the window
          ?? When thee CreateWindow function return ,windows create a window internal.What it means is that windows allocate a block memory to store the imformation about the window.If you want to show that ,you should call
          ShowWindow (hwnd, iCmdShow) ;
          UpdateWindow (hwnd) ;?
          ?4) The Message Loop
          ?while (GetMessage (&msg, NULL, 0, 0))
          ?{
          ???? TranslateMessage (&msg) ;
          ???? DispatchMessage (&msg) ;
          ?}

          ?typedef struct tagMSG
          {
          ???? HWND?? hwnd ;
          ???? UINT?? message ;// message identifier
          ???? WPARAM wParam ;
          ???? LPARAM lParam ;
          ???? DWORD? time ; // the time the message is placed on the message queen
          ???? POINT? pt ; // the mouse coordiante
          ?}
          ?typedef struct tagPOINT
          ?{
          ???? LONG? x ;
          ???? LONG? y ;
          ?}
          POINT, * PPOINT;
          the message filed of message retrived from the message queen is anyting except WM_QUITm ,GetMessage return a nonzero value
          wM_QUIT cause GetMessage reuturn 0.

          TranslateMessage (&msg) ;
          passing the msg struct back to window for some keysboard translation

          DispatchMessage (&msg) ;
          pass the msessageback to window .Windwo then send the message to the appropriate window procedure for processing.After window
          procedure processing the message ,it return control to the windows,which is still in serving the Dispatchmessage
          ?5) The Window Procedure
          ? a The window procedure determined the how the window display on the client area and how the window respose to user input
          ? b LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam),the four parameter is idential to the first four filed of the message struct.
          ?6) Processing the Message
          ?switch (iMsg)
          {
          case WM_CREATE :
          ???? [process WM_CREATE message]
          ???? return 0 ;
          ?????????
          case WM_PAINT :
          ???? [process WM_PAINT message]
          ???? return 0 ;
          ?????????
          case WM_DESTROY :
          ???? [process WM_DESTROY message]
          ???? return 0 ;
          }
          return DefWindowProc (hwnd, iMsg, wParam, lParam) ;

          when a window procedure process the message ,it should return 0;
          ?7) The WM_PAINT Message
          ? WU_PAINT message is extremely import in window.it inform a program when part or all of the window 's client area are invalid and must be redraw or repaint.
          ?WM_PAINT processing almost always begins with a call to BeginPaint:
          ? hdc = BeginPaint (hwnd, &ps) ; //return a handle to device context
          and ends with a call to EndPaint:
          ?EndPaint (hwnd, &ps) ;
          ?8)The WM_DESTROY Message
          ? PostQuitMessage (0) ;
          ??
          ?WNDCLASS, * PWNDCLASS ;
          ?#include <windows.h>
          /* the same as long _stdcall WndPro(long,unsign int,unsign int ,long)*/
          LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

          /*int _stdcall WinMain(long hInstance,long hPrevInstance,char * szComdLine,int iCmdShow)*/
          int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,???
          ??????????????????? PSTR szCmdLine, int iCmdShow)
          {
          ???? static TCHAR szAppName[] = TEXT ("HelloWin") ;
          ???? HWND???????? hwnd ;
          ???? MSG????????? msg ;
          ???? WNDCLASS???? wndclass ;
          /*
          ? all window createe based on this window class will completely repaint whenever? horizational window sizd and vertial??
          ? window size change.
          */
          ???? wndclass.style???????? = CS_HREDRAW | CS_VREDRAW ;?????????????????
          ???? wndclass.lpfnWndProc?? = WndProc ; // set the window procedure for the window class
          ???? wndclass.cbClsExtra??? = 0 ;
          ???? wndclass.cbWndExtra??? = 0 ;
          ???? wndclass.hInstance???? = hInstance ; // the handle of this program
          ???? wndclass.hIcon???????? = LoadIcon (NULL, IDI_APPLICATION) ;
          ???? wndclass.hCursor?????? = LoadCursor (NULL, IDC_ARROW) ;
          ???? wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
          ???? wndclass.lpszMenuName? = NULL ;
          ???? wndclass.lpszClassName = szAppName ;

          ???? if (!RegisterClass (&wndclass))
          ???? {
          ????????? MessageBox (NULL, TEXT ("This program requires Windows NT!"),
          ????????????????????? szAppName, MB_ICONERROR) ;
          ????????? return 0 ;
          ???? }
          ???? hwnd = CreateWindow (szAppName,????????????????? // window class name
          ????????????????????????? TEXT ("The Hello Program"), // window caption
          ????????????????????????? WS_OVERLAPPEDWINDOW,??????? // window style
          ????????????????????????? CW_USEDEFAULT,????????????? // initial x position
          ????????????????????????? CW_USEDEFAULT,????????????? // initial y position
          ????????????????????????? CW_USEDEFAULT,????????????? // initial x size
          ????????????????????????? CW_USEDEFAULT,????????????? // initial y size
          ????????????????????????? NULL,?????????????????????? // parent window handle
          ????????????????????????? NULL,?????????????????????? // window menu handle
          ????????????????????????? hInstance,????????????????? // program instance handle
          ????????????????????????? NULL) ;???????????????????? // creation parameters
          ????
          ???? ShowWindow (hwnd, iCmdShow) ;// iCmdShow determine how the window is to be initially displayed on the screen.
          ???? UpdateWindow (hwnd) ; // cause the client area to paint
          ????
          ???? while (GetMessage (&msg, NULL, 0, 0))
          ???? {
          ????????? TranslateMessage (&msg) ;
          ????????? DispatchMessage (&msg) ;
          ???? }
          ???? return msg.wParam ;
          }

          LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
          {
          ???? HDC???????? hdc ;
          ???? PAINTSTRUCT ps ;
          ???? RECT??????? rect ;
          ????
          ???? switch (message)
          ???? {
          ???? case WM_CREATE:
          ????????? PlaySound (TEXT ("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC) ;
          ????????? return 0 ;

          ???? case WM_PAINT:
          ????????? hdc = BeginPaint (hwnd, &ps) ;//return a handle to device context
          ?????????
          ????????? GetClientRect (hwnd, &rect) ;// set the struct rect with the dimensions of the client area
          ?????????
          ????????? DrawText (hdc, TEXT ("Hello, Windows 98!"), -1, &rect,
          ??????????????????? DT_SINGLELINE | DT_CENTER | DT_VCENTER) ;
          ????????? EndPaint (hwnd, &ps) ;
          ????????? return 0 ;
          ?????????
          ???? case WM_DESTROY:
          ????????? PostQuitMessage (0) ;// insert a WM_QIUT in the message queue.
          ????????? return 0 ;
          ???? }
          ???? return DefWindowProc (hwnd, message, wParam, lParam) ;
          }

          2 The Window Programming Hurdles
          ?1)Queue and noqueue message
          ? queue message are post the message queue and the noqueue message send to the window procdure directly.
          ????

          posted @ 2006-09-18 09:17 康文 閱讀(261) | 評論 (0)編輯 收藏

          Spring -transaction

          1 Understand Transaction
          ? 1) Introduce Spring's transaction manager
          ? a? JDBC transactions?
          ???? <bean id="transactionManager" class="org.springframework.jdbc.
          ????? datasource.DataSourceTransactionManager">
          ???? <property name="dataSource">
          ???? <ref bean="dataSource"/>
          ???? </property>
          ???? </bean>
          ?? b Hibernate transactions
          ???? <bean id="transactionManager" class="org.springframework.
          ?????? orm.hibernate.HibernateTransactionManager">
          ???? <property name="sessionFactory">
          ???? <ref bean="sessionFactory"/>
          ???? </property>
          ???? </bean>
          2 Programing transaction in Spring
          ?? One approach to adding transaction to your code is to programmly add transactional boundary using transiationTemplate class.
          ?? Programming is good when you want complete control over transactional boundary.but you have to use spring specific class.In most case ,your tansactional needs will not require such precise control over transactional boundaries.That is why you will typically choolse to declare transaction support
          ? public void enrollStudentInCourse() {
          ??? transactionTemplate.execute(
          ??? new TransactionCallback() {
          ????? public Object doInTransaction(TransactionStatus ts) {
          ??????? try {
          ????????? // do stuff?? Runs within doInTransaction()
          ??????? } catch (Exception e) {
          ????????? ts.setRollbackOnly(); //Calls setRollbackOnly() to roll Calls setRollbackOnly()???????????????????????????????? //to roll back
          ??????? }
          ????????? return null;?? //If successful, transaction is committed
          ????? }
          ??? }
          ?? );
          ?}
          ?<bean id="transactionTemplate" class="org.springframework.
          ?????? transaction.support.TransactionTemplate">
          ? <property name="transactionManager">
          ??? <ref bean="transactionManager"/>
          ? </property>
          ?</bean>
          ?<bean id="courseService"
          ??? class="com.springinaction.training.service.CourseServiceImpl">
          ?<property name=" transactionTemplate">
          ???? <ref bean=" transactionTemplate"/>
          ?? </property>
          ?</bean>
          3 Declaring transactions
          ? Spring's support for declarative transaction management is implementedd through Spirng's? AOP framework.
          ? <bean id="courseService" class="org.springframework.transaction.
          ?????? interceptor.TransactionProxyFactoryBean">
          ? <property name="proxyInterfaces">
          ??? <list>
          ????? <value>
          ??????? com.springinaction.training.service.CourseService??
          ????? </value>
          ??? </list>
          ? </property>
          ? <property name="target">
          ?? <ref bean="courseServiceTarget"/>?? //Bean being proxied
          ? </property>
          ?<property name="transactionManager">
          ?? <ref bean="transactionManager"/>?? //Transaction manager
          ?</property>
          ?<property name="transactionAttributeSource">
          ?? <ref bean="attributeSource"/>?? //Transaction attribute source
          ?</property>
          ?</bean>
          ?1) Understanding transaction attributes
          ? In Spring transaction attribute is a description of how transaction policies should be
          applied to a methods
          ?? a? Propagation behavior
          ??? Propagation behavior???????????????? What it means
          ??? PROPAGATION_MANDATORY??????????????? indicate that the method must run within a????????????????????????????????????????????????? transaction.If no transaction is in progress
          ???????????????????????????????????????? an exception will be thrown
          ??? PROPAGATION_NESTED
          ??? PROPAGATION_NEVER??????????????????? indicate that the method can not run withi a??????????????????????????????????????????????? transaction. if a transaction exist an exception??????????????????????????????????????????? will be thrown.
          ??? PROPAGATIOM_NOT_SUPPORT????????????? Indicates that the method should not run within a?????????????????????????????????????????? transaction. If an existing transaction is????????????????????????????????????????????????? in progress, it will be suspended for the
          ???????????????????????????????????????? duration of the method.
          ??? PROPAGATION_REQUIRED???????????????? indicate that the current method must run within a????????????????????????????????????????? transaction.if an existing transaction is in??????????????????????????????????????????????? progress,the ,method will run with the transaction
          ???????????????????????????????????????? otherwise a new transaction will be started
          ??? PROPAGATION_REQUIRENEW?????????????? indicates that the current must run within its own
          ???????????????????????????????????????? transaction.A new transaction is started and an???????????????????????????????????????????? existing transaction will be suspend
          ??? PROPAGATION_SUPPORT????????????????? indicate the current mehtod does not require a????????????????????????????????????????? transaction.but may run if on is already in progress?????
          ??? b Isolation levels?????
          ??? Isolation level??????????????????? What it means
          ??? ISOLATION_DEFAULT????????????????? Using the defaul isolation level of the underlying????????????????????????????????????????? database
          ??? ISOLATION_READ_UNCOMMITTED???????? Allows you read change that have not yet been commit
          ?????????????????????????????????????? May result in dirty read,phantom read,nonrepeatable???????????????????????????????????????? read
          ??? ISOLATION_READ_COMMITTED?????????? Allows reads from concurrent transactions that have
          ?????????????????????????????????????? bean committed.Dirty read are prevent.but platform????????????????????????????????????????? and norepeatable reads may still occur.
          ??? ISOLATIOM_REPEATABLE_READ????????? Multiple read the same field will yield the same??????????????????????????????????????????? result ,unless changed by the transaction?????????????????????????????????????????????????? itself.Dirty reads ,nonrepeatable are all prevented
          ?????????????????????????????????????? phantom may still occur
          ??? ISOLATION_SERIALIZABLE???????????? This fully ACID-compliant isolation level ensusme??????????????????????????????????????? that dirty read,unrepeatable read ,phantom read are??????????????????????????????????????? all prevented.And this is the most slowest isolation
          ?????????????????????????????????????? since it is typically accomplished by doing full??????????????????????????????????????? table lock on the tables in the transaction.

          ?? c Read-Only
          ?? If a transaction performs only read operation against the underlying datastore.when a transaction begin ,it only make sense to declare a transaction as read only on mehtods with
          propagation behavior which start a new transaction.
          ?? Furthermore ,if you are Hibernate as persistence mechanism,declaring a transaction as read only will reult in Hibernate flush mode being set to FLUST_NEVER.this tell hibernate to avoid synchroniztion of objects with database.
          ?? d Transaction timeout
          ?? Suppose that your transaction becomes unexpectedly long-running transaction.Because transaction may invole locks on the underlying database.Instead of waiting it out ,you can delcare a transaction to automaitically roll back.
          ?? because timeout clock begin ticking when a transaction start. it only make sense to declare a transaction timeout on methods with propagation behavior that start a new transaction.
          ? 2) Declaring a simple transaction policy
          ?? <bean id="myTransactionAttribute"
          ??? class="org.springframework.transaction.interceptor.
          ??????????? DefaultTransactionAttribute">
          ? <property name="propagationBehaviorName">
          ??? <value>PROPAGATION_REQUIRES_NEW</value>
          ? </property>
          ? <property name="isolationLevelName">
          ??? <value>ISOLATION_REPEATABLE_READ</value>
          ? </property>
          ?</bean>
          ?<bean id="transactionAttributeSource"
          ??? class="org.springframework.transaction.interceptor.
          ??????????? MatchAlwaysTransactionAttributeSource">
          ? <property name="transactionAttribute">
          ??? <ref bean="myTransactionAttribute"/>
          ? </property>
          ?</bean>
          4 Declaring transactions by method name
          ? 1) Using NameMatchTransactionAttributeSource
          ? The properties property of NameMatchTransactionAttributeSource maps mehtod to a transaction property descriptor. the property descriptor takes the following form:
          ? Propagation,isolation,readOnly,-Exception,+Exception
          ?
          ? <bean id="transactionAttributeSource"
          ??? class="org.springframework.transaction.interceptor.
          ??????????? NameMatchTransactionAttributeSource">
          ? <property name="properties">
          ??? <props>
          ????? <prop key="enrollStudentInCourse">
          ????????? PROPAGATION_REQUIRES_NEW
          ????? </prop>
          ??? </props>
          ? </property>
          ?</bean>
          ?2) Specifying the transaction Isolation level
          ? <bean id="transactionAttributeSource"
          ??? class="org.springframework.transaction.interceptor.
          ??????????? NameMatchTransactionAttributeSource">
          ???? <property name="properties">
          ??? <props>
          ????? <prop key="enrollStudentInCourse">
          ??????? PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ
          ????? </prop>
          ??? </props>
          ? </property>
          ?</bean>
          ?3) Using real-only transaction
          ? <bean id="transactionAttributeSource"
          ??? class="org.springframework.transaction.interceptor.
          ??????????? NameMatchTransactionAttributeSource">
          ? <property name="properties">
          ??? <props>
          ????? <prop key="getCompletedCourses">
          ??????? PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ,readOnly
          ????? </prop>
          ??? </props>
          ? </property>
          </bean>
          ?4)Specifying? rollback rules
          ? You can sepcify that a transaction be rollback on specify checked exception
          ? <bean id="transactionAttributeSource"
          ??? class="org.springframework.transaction.interceptor.
          ??????????? NameMatchTransactionAttributeSource">
          ? <property name="properties">
          ??? <props>
          ????? <prop key="enrollStudentInCourse">
          ??????? PROPAGATION_REQUIRES_NEW,ISOLATION_REPEATABLE_READ,
          ??????? -CourseException
          ??????? </prop>
          ???? </props>
          ??? </property>
          ? </bean>
          ? Exception can be marked as negative(-) or postive(+)
          ? Negative exception will trigger the roll back if the exception (or sublclass of it) is thrown.Postive exception on the other hand indicate that the transacton should be commit
          even if the exception is thrown
          ?5)Using wildcard matches
          ?<bean id="transactionAttributeSource"
          ??? class="org.springframework.transaction.interceptor.
          ??????????? NameMatchTransactionAttributeSource">
          ? <property name="properties">
          ??? <props>
          ????? <prop key="get*">
          ??????? PROPAGATION_SUPPORTS
          ????? </prop>
          ??? </props>
          ? </property>
          </bean>
          ?6 Short-cut name match transaction
          ?<bean id="courseService" class="org.springframework.transaction.
          ?????? interceptor.TransactionProxyFactoryBean">
          ?? <property name="transactionProperties">
          ??? <props>
          ????? <prop key="enrollStudentInCourse">
          ??????? PROPAGATION_REQUIRES_NEW
          ????? </prop>
          ??? </props>
          ?? </property>
          ?</bean>

          posted @ 2006-09-15 11:00 康文 閱讀(1804) | 評論 (0)編輯 收藏

          window programming --Unicode

          一 Unicode 簡介
          ?1 Unicode 是ASCII 擴展,從傳統的7位,擴展位16 位,可以顯示世界上所有語言
          ASCII 碼
          ?????? 0-???? 1-???? 2-???? 3-???? 4-???? 5-???? 6-???? 7-
          -0???? NUL??? DLE??? SP???? 0????? @????? P????? `????? p
          -1???? SOH??? DC1??? !????? 1????? A????? Q????? a????? q
          -2???? STX??? DC2??? "????? 2????? B????? R????? b????? r
          -3???? ETX??? DC3??? #????? 3????? C????? S????? c????? s
          -4???? EOT??? DC4??? $????? 4????? D????? T????? d????? t
          -5???? ENQ??? NAK??? %????? 5????? E????? U????? e????? u
          -6???? ACK??? SYN??? &????? 6????? F????? V????? f????? v
          -7???? BEL??? ETB??? '????? 7????? G????? W????? g????? w
          -8???? BS???? CAN??? (????? 8????? H????? X????? h????? x
          -9???? HT???? EM???? )????? 9????? I????? Y????? I????? y
          -A???? LF???? SUB??? *????? :????? J????? Z????? j????? z
          -B???? VT???? ESC??? +????? ;????? K????? [????? k????? {
          -C???? FF???? FS???? ,????? <????? L????? \????? l????? |
          -D???? CR???? GS???? -????? =????? M????? ]????? m????? }
          -E???? SO???? RS???? .????? >????? N????? ^????? n????? ~
          -F???? SI???? US???? /????? ?????? O????? _????? o????? DEL

          ?2 雙位字符集
          DBCS:double-byte character set,最初的128個代碼是ASCII,較高的128個代碼中的某些總是跟隨著第

          二個位元組。這兩個位元組一起(稱作首位元組和跟隨位元組)定義一個字元。

          ?3 Unicode 解決方案
          ? Unicode是統一的16位元系統,也DBCS 這樣的同時含有一位和兩位的字符集不同,Unicode 可以表示

          65536 個字符。
          ? Unicode 的缺點是,Unicode 使用的空間是ASCII 的兩倍
          二 寬字符和c
          ?1 char
          ? char c='A';
          ? 變量c 用一個字節來存儲,用16 進制表示位0x41
          ? char * p;
          ? 32 位系統,一次指針變量需要用4個字節表示
          ? char * p="Hello!";
          ? 字符串占用7個字節 其中 6個用于保存字符串,1個用于保存中止符號0
          ? char [10]
          ? 占用10個字節
          ? char a[]="Hello!";
          ? 占用 7個字節
          ?2 寬字節
          ? typedef unsigned short whcar_t?? which is define in the window.h?
          ? 與unsign short 一樣 為16 字節,兩個字節
          ? wchar_t c='A'?? 0x0041
          ? wchar_t *p=L"Hello!"? 指針占用 4個字節 而 字符串占用 14 個字節
          ?3 寬字元程序庫函數
          ? char * pc = "Hello!" ;
          ? iLength = strlen (pc) ;
          ? wchar_t * pw = L"Hello!" ;
          ? iLength = wcslen (pw) ;
          ?4 維護單一原始碼
          ?Microsoft Visual C++包含的TCHAR.H
          ?如果定義了名為_UNICODE的識別字,并且程式中包含了TCHAR.H表頭檔案,那么_tcslen就定義為wcslen
          ?#define _tcslen wcslen
          ?如果沒有定義UNICODE,則_tcslen定義為strlen:
          ?#define _tcslen strlen
          ?如果定義了 _UNICODE識別字,那么TCHAR就是wchar_t:
          ?typedef wchar_t TCHAR ;
          ?否則,TCHAR就是char:
          ?typedef char TCHAR ;

          ?如果沒有定義_UNICODE識別字
          ?#define __T(x) x
          ?#define _T(x) __T(x)
          ?#define _TEXT(x) __T(x)

          三 寬字節和windows
          ? 1 window 頭文件中的類型
          ? typedef char CHAR ;
          ? typedef wchar_t WCHAR ;
          ? typedef CHAR * PCHAR, * LPCH, * PCH, * NPSTR, * LPSTR, * PSTR ;
          ? typedef CONST CHAR * LPCCH, * PCCH, * LPCSTR, * PCSTR ;
          ? typedef WCHAR * PWCHAR, * LPWCH, * PWCH, * NWPSTR, * LPWSTR, * PWSTR ;
          ? typedef CONST WCHAR * LPCWCH, * PCWCH, * LPCWSTR, * PCWSTR ;

          ? #ifdef? UNICODE??????????????????
          ? typedef WCHAR TCHAR, * PTCHAR ;
          ? typedef LPWSTR LPTCH, PTCH, PTSTR, LPTSTR ;
          ? typedef LPCWSTR LPCTSTR ;
          ? #else
          ? typedef char TCHAR, * PTCHAR ;
          ? typedef LPSTR LPTCH, PTCH, PTSTR, LPTSTR ;
          ? typedef LPCSTR LPCTSTR ;
          ? #endif
          ? 2 Windows 函數調用
          ? #ifdef UNICODE
          ? #define MessageBox? MessageBoxW
          ? #else
          ? #define MessageBox? MessageBoxA
          ? #endif
          ? 3 Windows 的字符函數
          ? ILength = lstrlen (pString) ;
          ? pString = lstrcpy (pString1, pString2) ;
          ? pString = lstrcpyn (pString1, pString2, iCount) ;
          ? pString = lstrcat (pString1, pString2) ;
          ? iComp = lstrcmp (pString1, pString2) ;
          ? iComp = lstrcmpi (pString1, pString2) ;
          ? 4 在windows 使用printf
          ?? windows 并不支持printf 但是可以使用sprintf
          ?? int printf (const char * szFormat, ...) ;
          ?? printf ("The sum of %i and %i is %i", 5, 3, 5+3) ;
          ?? int sprintf (char * szBuffer, const char * szFormat, ...) ;
          ?? char szBuffer [100] ;
          ?? sprintf (szBuffer, "The sum of %i and %i is %i", 5, 3, 5+3) ;
          ?? puts (szBuffer) ;

          posted @ 2006-09-14 15:12 康文 閱讀(221) | 評論 (0)編輯 收藏

          spring -database

          一 Spring DAO philosophy
          ?1 Understanding Spring's DataAccesssException
          ?Spring's DAO frameworks donot throw teechnology-specific exceptions such as SQLException
          or HibernateeExcepiton.Instead ,all exceptions thrown are subclasses of DataAccessException
          ?2 You are not forced to handle DataAccessExceptions
          ?DataAccessException is a RuntimeException,so it si an unchecked exception.Since these are quite often unrecoverable,you are not forced to handle these exception.
          ? Instead ,you can catch the exception if recovery is possible.since DataAccessException is not only a RuntimeException,but it subclasses Spring's NestedRuntimeException. This menas that the root Exception is alwarys via NestedRuntimeException's getCause() method.
          ?3 Work with DataSources
          ? a getting a Datasource from JNDI
          ?? <bean id="dataSource"
          ????? class="org.springframework.jndi.JndiObjectFactoryBean">
          ?? <property name="jndiName">
          ??? <value>java:comp/env/jdbc/myDatasource</value>
          ?? </property>
          ?? </bean>
          ? b Creating a Datasource connection pool
          ?? <bean id="dataSource"
          ????? class="org.apache.commons.dbcp.BasicDataSource">
          ? <property name="driver">
          ??? <value>${db.driver}</value>
          ? </property>
          ? <property name="url">
          ??? <value>${db.url}</value>
          ? </property>
          ? <property name="username">
          ??? <value>${db.username}</value>
          ? </property>
          ? <property name="password">
          ??? <value>${db.password}</value>
          ? </property>
          </bean>
          ?c Using a DataSource while testing
          ? DriverManagerDataSource dataSource = new DriverManagerDataSource();
          ? dataSource.setDriverClassName(driver);
          ? dataSource.setUrl(url);
          ? dataSource.setUsername(username);
          ? dataSource.setPassword(password);
          ?4 Consistent DAO support
          ? Spring template class handle the invariant part of data access-controling the trancsaction
          manage resource,handling exception .Implementation of callback interface define what is specific to your application--creating statement,binding parameter and marshalling result set.
          ?Spring separates the fixed an vaiant parts of data access process into tow distince classes:
          template and callbacks.Template manage the fixed parts of the process while callback are where you fill in the implement details;
          ?one the top of template-callback desing ,spring framework provide a support class which your own data access subclass it. And the support class already have a property for holding a template.
          ?二 Integerating Hibernate with Spring
          ? 1 Managing Hibernate resources
          ?? you will keep a single instance of SessionFactory throughtout your application
          ?? <bean id="sessionFactory"class="org.springframework.
          ?????????? orm.hibernate.LocalSessionFactoryBean">
          ???? <bean id="sessionFactory" class="org.springframework.
          ?????? orm.hibernate.LocalSessionFactoryBean">
          ???? <property name="dataSource">
          ?????? <ref bean="dataSource"/>
          ???? </property>
          ? </bean>
          ? you also want to manager how hibernate is configured
          ? <bean id="sessionFactory" class="org.springframework.
          ?????? orm.hibernate.LocalSessionFactoryBean">
          ? <property name="hibernateProperties">
          ??? <props>
          ????? <prop key="hibernate.dialect">net.sf.hibernate.
          ?????????? dialect.MySQLDialect</prop>

          ??? </props>
          ? </property>
          ? …
          ?</bean>
          ?and the last thing is whick map files is read
          ? <bean id="sessionFactory" class="org.springframework.
          ?????? orm.hibernate.LocalSessionFactoryBean">
          ? <property name="mappingResources">
          ???? <list>
          ???? <value>Student.hbm.xml</value>
          ???? <value>Course.hbm.xml</value>
          ???? …
          ?? </list>
          ? </property>
          ???? …
          ? </bean>

          ?Now? you have fully configured your sessionfactory ,so we need do create an object which we
          will access hibernate. As we know, we will use a template class
          ? <bean id="hibernateTemplate"
          ????? class="org.springframework.orm.hibernate.HibernateTemplate">
          ? <property name="sessionFactory">
          ??? <ref bean="sessionFactory"/>
          ? </property>
          ?</bean>

          ? <bean id="courseDao" class="com.springinaction.
          ?????? training.dao.hibernate.CourseDaoHibernate">
          ? <property name="hibernateTemplate">
          ??? <ref bean="hibernateTemplate"/>
          ? </property>
          ?</bean>

          ?2 Accessing Hibernate through HibernatTemplate
          ? The template-callback mechanism in Hibernatee is pretty simple.There is the HibernatTmpplate and one callback interface
          ? public Student getStudent(final Integer id) {
          ? return (Student) hibernateTemplate.execute(
          ??? new HibernateCallback() {
          ????? public Object doInHibernate(Session session)
          ????????? throws HibernateException {
          ??????? return session.load(Student.class, id);
          ????? }
          ??? });
          ?
          ? The HibernateTemplate class provides some convience methods that implicit create a HibernateCallback instance:
          ? (Student) hibernateTemplate.load(Student.class, id);
          ?? hibernateTemplate.update(student);
          ? hibernateTemplate.find("from Student student " +
          ??????????????????????????????? "where student.lastName = ?",
          ??????????????????????????????? lastName, Hibernate.STRING);
          ? 3 Subclassing HibernateDaoSupport
          ? public class StudentDaoHibernate extends HibernateDaoSupport
          ??? implements StudentDao {
          ? …
          ? }
          ? getHibernateTemplate()
          ? getSession()

          posted @ 2006-09-14 11:45 康文 閱讀(271) | 評論 (0)編輯 收藏

          hibernate 一級緩存

          1 hibernate 一級緩存
          Session?
          ? evict(Object o) 從緩存中清除指定的持久化對象
          ? clear()???????? 清除緩存中所有對象
          2 批量更新于批量刪除
          ? 1) 批量更新
          ?? Iterator customers=session.find("from Customer c where c.age>0");
          ?? while(customers.hasNext()){
          ???? Customer customer=(Customer)customers.next();
          ???? customer.setAge(customer.getAge()+1);
          ?? }
          ?? tx.commit();
          ?? session.close();

          ? 缺點:內存中加載了大量數據
          ??????? 執行了多次update 語句
          ?
          ?? 改進
          ?? Iterator customers=session.find("from Customer c where c.age>0");
          ?? while(customers.hasNext()){
          ???? Customer customer=(Customer)customers.next();
          ???? customer.setAge(customer.getAge()+1);
          ???? session.flush();
          ???? session.evict(customer);
          ?? }
          ?? tx.commit();
          ?? session.close();
          ?? 遺留問題
          ?? 執行了多次update 語句
          ??
          ?? 采用jdbc api 進行調用
          ?? Connection con=session.connection();
          ?? PrepareStatement stmt=con.prepareStatement("update customers set age=age+1 where age>0");
          ?? stmt.executeUpdate();
          ?? tx.commit();
          ?? 另外,也可以調用底層的存儲過程進行批量更新
          ?? create or replace procedure batchUpdateCustomer(p_age,in number) as
          ?? begin
          ????? update customer set age=age+1 where age>p_age;
          ?? end;
          ??
          ?? tx=session.beginTransaction();
          ?? Connection con=session.connection();
          ?? CallableStatement cstmt=con.prepareCall(batchUpdateCustomer);
          ?? cstmt.setInt(1,0);
          ?? cstmt.eqecuteUpdate();
          ?? tx.commit();
          ?? 2) 批量數據的刪除
          ??? session.delete("from? Customer c where c.age>0");
          ??? 實際調用的過程
          ??? session * from Customer where age>0;
          ??? 在把所有數據加載到內存之后執行多條delete 語句
          ??? delete from customer where id=i;
          ???? .......................
          ?? 改進辦法采用jdbc api 進行批量數據的刪除
          ?????
          ?? tx=session.beginTransaction();
          ?? Connection con=session.connection();
          ?? con.execute("delete from customers where age>0");
          ?? tx.commit();

          posted @ 2006-09-14 09:22 康文 閱讀(466) | 評論 (0)編輯 收藏

          hibernate -類型

          Hibernate????????????????? java???????????????????? sql??????????????????? oracle???????

          integer or int???????????? int or Integer?????????? INTEGER
          long?????????????????????? long or Long???????????? BIGINT
          short????????????????????? short or Short?????????? SMALLINT
          byte?????????????????????? byte or Byte???????????? TINYINT
          float????????????????????? float or Float?????????? FLOAT
          double???????????????????? double or Double???????? DOUBLE
          big_decimal??????????????? java.math.BigDecimal???? NUMBERBIC
          character????????????????? char java.lang.Character CHAR(1)
          ?????????????????????????? String?????????????????????
          string???????????????????? String??????????????????? VARCHAR
          boolean??????????????????? boolean or Boolean??????? BIT
          date?????????????????????? java.util.Date??????????? DATE
          ?????????????????????????? java.sql.Date
          time?????????????????????? Date or java.sql.time???? TIME
          timestamp????????????????? Date or java.sql.Timestamp TIMESTAMP??????????????
          binary???????????????????? byte[]??????????????????? blog?????????????????? blog
          text?????????????????????? String??????????????????? clob?????????????????? clog
          serializable???????????????????????????????????????? blog?????????????????? blog????????????
          clob?????????????????????? java.sql.clob??????????? clob??????????????????? clob
          blob?????????????????????? java.sql.blob???????????? blog?????????????????? blob

          posted @ 2006-09-14 09:20 康文 閱讀(334) | 評論 (0)編輯 收藏

          windows programming -jump from start.txt

          1 動態連接
          Windows 運作機制的核心是一個稱作動態連接的概念


          #include <windows.h>
          int WINAPI WinMain (?HINSTANCE hInstance, HINSTANCE hPrevInstance,
          ???PSTR szCmdLine, int iCmdShow)
          {
          MessageBox (NULL, TEXT ("Hello, Windows 98!"), TEXT ("HelloMsg"), 0);
          return 0 ;
          }

          ?1) #include <windows.h>包含其它的頭文件
          ?2) 程序入口
          ?? int WINAPI WinMain (?HINSTANCE hInstance,HINSTANCE hPrevInstance,
          ??????????? ?PSTR szCmdLine,int iCmdShow)

          ?? a #define WINAPI __stdcall? 指定一個呼叫約定,包括如何生產機器碼,參數如何入棧
          ?? b HINSTANCE hInstance 執行體代號,唯一標識該程序
          ?? c HINSTANCE hPrevInstance 已經不采用
          ?? d PSTR szCmdLine 參數列表
          ?? e int iCmdShow 顯示方式
          ? 3) MessageBox 函數
          ?? MessageBox (NULL, TEXT ("Hello, Windows 98!"), TEXT ("HelloMsg"), 0);
          ?? 參數1 窗體代號
          ?? 參數2 主題顯示文字
          ?? 參數3 標題顯示文字
          ?? 參數4 按鈕,0 為確認 使用C語言的OR(|)操作符號將上面顯示的一個常數與代表內定按鈕的常數組合:

          ?
          #define ?MB_OK?????????????????????? ????0x00000000L
          #define ?MB_OKCANCEL???????????????? ????0x00000001L
          #define ?MB_ABORTRETRYIGNORE???????? ????0x00000002L
          #define ?MB_YESNOCANCEL????????????? ????0x00000003L
          #define ?MB_YESNO??????????????????? ????0x00000004L
          #define ?MB_RETRYCANCEL?

          #define ?MB_DEFBUTTON1?????????????? ????0x00000000L
          #define ?MB_DEFBUTTON2?????????????? ????0x00000100L
          #define ?MB_DEFBUTTON3?????????????? ????0x00000200L
          #define ?MB_DEFBUTTON4

          圖示的外觀
          #define ?MB_ICONHAND???????????????? ?????? 0x00000010L
          #define ?MB_ICONQUESTION???????????? ????????? 0x00000020L
          #define ?MB_ICONEXCLAMATION????????? ????????? 0x00000030L
          #define ?MB_ICONASTERISK

          #define ?MB_ICONWARNING????????????? ?MB_ICONEXCLAMATION
          #define ?MB_ICONERROR??????????????? ?MB_ICONHAND
          #define ?MB_ICONINFORMATION????????? ?MB_ICONASTERISK
          #define ?MB_ICONSTOP

          2 c 語言編譯過程 c--compile --?? .obj?? ---linking----? .exe

          posted @ 2006-09-13 16:37 康文 閱讀(226) | 評論 (0)編輯 收藏

          c++ builder 文件的操作

          一 文件
          ?? 1 c 標準文件驅動器,可以支持兩種文件類型,二進制文件,和文本文件。c 標準文件是在頭文件

          stdio.h 中聲明。
          標準文件類型通過指針來進行存儲 FILE * fp;
          ?? 2 c++ 流式文件類 fstream,ifstream 和ofstream,分別對應讀寫,讀和寫,并支持文本和二進制文

          件。
          ?? 3 非緩沖文件
          二 文件對話框組件
          ?? 1 OpenDialog 兩種.TXT and .PAS 兩種類型的過濾器。
          ???? 1) Filter OpenDaalog1->Filter="Text files{*.txt}|*.TXT|Pascal files{*.pas}|*.PAS";
          ? 同一個過濾器中,還可以有多種文件后綴
          ????? OpenDialog1->Filter="Pascal files|*.PAS;*.DPK;*.DPR";
          ???? 2) FilterIndex 設置對話框一打開時選中的文件過濾。數值從1開始計算。
          ???? 3) InitialDir 設置對話框打開時定位的目錄。
          ???? 4) Options
          ?????? OpenPictureDialog1->Options.Clear();
          ?????? OeenPictureDialog1->Options<<ofFileMustExist<<ofHideReadOnly<<ofNoChangeDir;
          ???? 5) Title 設置對話框標題中顯示的內容。
          ?? 2 SaveDialog 組建可以選擇并保存文件
          ?? 3 OpenPictureDialog 可以選擇并打開圖形文件。
          ?? 4 SavePictureDialog 可以選擇并保存圖形文件。
          三 Win3。1 相關組件
          ?? FileListBox,DirectoryListBox,DriveCombox,FilterComboBox
          四 常用文件管理函數
          ? 1 文件函數常用函數
          ? 將一個文件從記錄盤上刪除,如果不存在或無法刪除。則返回False。
          ? extern PACKAGE bool __fastcall DeleteFile(const AnsiString FileName);
          ? void __fastcall TFORM1::ButtonClick(TObject *Sender)
          ? {
          ????? char buffer[256];
          ????? GetWindowsDirectory(buffer,sizeof(buffer));//獲取Windows 系統目錄
          ???? AnsiString asFileName=FileSearch(Edit1->Text,GetCurrentDir()+AnsiString(";")

          +AnsiString(buffer));//在當前目錄下和windows系統}//目錄下查詢文件。?
          ? if(asFileName.IsEmty()) ShowMessage(AnsiString("Couldn't Found")+Edit1->Text1);
          ? 2 FileSeek
          ? extern PACKAGE int __fastcall FileSeek(int Handle, int Offset, int Origin);
          ? extern PACKAGE __int64 __fastcall FileSeek(int Handle, const __int64 Offset, int Origin);

          ? Description

          ? Use FileSeek to reposition the read/write point in a file that was opened with FileOpen or

          FileCreate. Handle is the file handle that was returned by FileOpen or FileCreate.

          ? Offset specifies the number of bytes from Origin where the file pointer should be

          positioned. Origin is a code with three possible values, denoting the beginning of the file,
          ? the end of the file, and the current position of the file pointer.

          ? Origin?Action

          ? 0?The file pointer is positioned Offset bytes from the beginning of the file.
          ? 1?The file pointer is positioned Offset bytes from its current position.
          ? 2?The file pointer is positioned Offset bytes from the end of the file.

          ? If FileSeek is successful, it returns the new position of the file pointer; otherwise, it

          returns -1.
          ?? void __fastcall TForm1::Button1Click(TObject *Sender)

          {
          ? int iFileHandle;
          ? int iFileLength;
          ? int iBytesRead;
          ? char *pszBuffer;
          ? if (OpenDialog1->Execute())
          ? {
          ??? try
          ??? {
          ????? iFileHandle = FileOpen(OpenDialog1->FileName, fmOpenRead);
          ????? iFileLength = FileSeek(iFileHandle,0,2);
          ????? FileSeek(iFileHandle,0,0);
          ????? pszBuffer = newchar[iFileLength+1];
          ????? iBytesRead = FileRead(iFileHandle, pszBuffer, iFileLength);
          ????? FileClose(iFileHandle);

          ????? for (int i=0;i<iBytesRead;i++)
          ????? {
          ??????? StringGrid1->RowCount += 1;
          ??????? StringGrid1->Cells[1][i+1] = pszBuffer[i];
          ??????? StringGrid1->Cells[2][i+1] = IntToStr((int)pszBuffer[i]);
          ????? }
          ????? delete [] pszBuffer;
          ??? }
          ??? catch(...)
          ??? {
          ????? Application->MessageBox("Can't perform one of the following file operations: Open,

          Seek, Read, Close.", "File Error", IDOK);
          ??? }
          ? }
          }
          ?3FileExists
          ? if(FileExist(SaveDialog1->FileName))
          ?{
          ?? RenameFile(SaveDialog1->File,SaveDialog1->FileName+".bak");
          ?}
          ?iFileHandle=fileCreate(SaveSialog1->FileName);
          ?for(int i=0;i<Memo2->Lines->String[i].length())
          ?{
          ?? FileWrite(iFileHandle,Memo2->Lines->String[i].c_str(),length);
          ?}
          ?FileClose(iFileHandle);
          ? 4 FileGetAttrs
          ? FileGetAttr returns the attributes of the file as a string of bits. This value is the same

          as the Attr field of a TSearchRec struct. Check for individual attributes with code such as

          the following:
          ? int Attrs = FileGetAttr("MyFile.sys");
          ? if x(Attrs & faHidden)
          ? FileSetAttr("MyFile.sys", Attrs & !faHidden);
          ? A return value of -1 indicates that an error occurred.
          ? 5 FileSetAttrs
          ? FileSetAttr sets the file attributes of the file given by FileName to the value given by

          Attr. The value of Attr is formed by combining the appropriate file attribute constants, as

          in the following:
          ? FileSetAttr("MyFile.sys", faReadOnly | faSysFile);
          ? FileSetAttr returns zero if the function was successful. Otherwise the return value is an

          error code.
          三 目錄操作常用函數
          ? 1 CreateDir
          ???? #include <Filectrl.hpp>
          ?? void __fastcall TForm1::Button1Click(TObject *Sender)

          ?? {
          ????? if (!DirectoryExists("c:\\temp"))
          ????? {
          ??????????? if (!CreateDir("C:\\temp"))
          ??????????? throw Exception("Cannot create c:\\temp directory.");
          ????? }
          ?? }
          ?? 2 ForceDirectories
          ?? ForceDirectories creates a new directory as specified in Dir, which must be a fully-

          qualified path name. If the directories given in the path do not yet exist, ForceDirectories

          attempts to create them.
          ?? ForceDirectories returns true if it successfully creates all necessary directories, false

          if it could not create a needed directory.
          ?? Important
          ?? Do not call ForceDirectories with an empty string. Doing so causes ForceDirectories to

          throw an exception.?
          ?? void __fastcall TForm1::Button1Click(TObject *Sender)
          ?? {
          ???????? AnsiString Dir = "C:\Apps\Sales\Local";
          ???????? if (ForceDirectories(Dir))
          ???????? Label1->Caption = Dir + " was created";
          ?? }
          ?? 3 GetCurrentDir
          ?? 獲取當前的目錄完整的路徑名
          ?? 4 RemoveDir
          ?? 刪除一個存在的目錄,目錄必須為空
          ?? 5 SetCurrentDir設置系統的當前目錄
          ?? 6 SelectDirectory
          ?? extern PACKAGE bool __fastcall SelectDirectory(constAnsiString Caption, const WideString

          Root, AnsiString &Directory);
          ?? Call SelectDirectory to let the user enter a directory name.??
          ?? Use the first syntax to display the Windows directory browser. The Caption parameter

          specifies a caption for the dialog. The Root parameter specifies the root directory from

          which to browse. The selected directory is returned as the Directory parameter. When using

          this syntax,
          ?? SelectDirectory does not change the value of the current directory.
          ??
          ?? extern PACKAGE bool __fastcall SelectDirectory(AnsiString &Directory, TSelectDirOpts

          Options, int HelpCtx);
          ?? enum TSelectDirOpt { sdAllowCreate, sdPerformCreate, sdPrompt };
          ?? typedef Set<TSelectDirOpt, sdAllowCreate, sdPrompt>? TSelectDirOpts;
          ??
          ?? sdAllowCreate?An edit box allows the user to type in the name of a directory that
          ??????????????????????? does not exist. This option does not create a directory: the

          application
          ??????????????????????? must read the name of the selected directory and create it i
          ????????????????????? f desired.
          ?? sdPerformCreate?Used only in combination with sdAllowCreate. If the user enters a

          directory
          ??????????????????????? name that does not exist, the directory selection dialog creates it.
          ?? sdPrompt??????? Used only in combination with sdAllowCreate. Displays a message box
          ?????????????????????? that informs the user when the entered directory does not exist
          ?????????????????????? and asks if the directory should be created.
          ?????????????????????? If the user chooses OK, the directory is created
          ?????????????????????? if the option set includes sdPerformCreate.
          ?????????????????????? If the option set does not include sdPerformCreate,
          ?????????????????????? the directory is not created:
          ??????????????? the application must read the directory name and create
          ??? #include <FileCtrl.hpp>
          ??? void __fastcall TForm1::Button1Click(TObject *Sender)
          ?? {
          ????? AnsiString Dir = "C:\\Program Files\\MyApp";
          ????? if (SelectDirectory(Dir, TSelectDirOpts() << sdAllowCreate << sdPerformCreate <<

          sdPrompt,1000))
          ????? Label1->Caption = Dir;

          ?? }
          三 驅動器常用函數
          ? 1 DiskFree 指定驅動器中剩余空間的字節數
          ? 2 DiskSize 驅動器容量
          四文件名常用函數
          ? 1 ChangeFileExt
          ? 2 ExtractFileDir
          ? 3 ExtractFileDriver
          ? 4 ExtractFileExt
          ? 5 ExtractFileName
          ? 6 ExtractFilePath
          ? 7 ExtractRelativePath
          實例
          1
          ?? 1
          L a b e l 1 目錄列表( & D ) : FocusControl: DirectoryListBox1
          D i r e c t o r y L i s t B o x 1 D i r L a b e l : L a b e l 6 ;
          ??????????????????????????????????????????????????? FileList: FileListBox1
          L a b e l 2 文件列表( & S ) : FocusControl: FileListBox1
          F i l e L i s t B o x 1 FileEdit: Edit1
          L a b e l 3 驅動器( & R ) : FocusControl: DriveComboBox1
          D r i v e C o m b o B o x 1 DirList: DirectoryListBox1
          L a b e l 4 文件類型( & F ) : FocusControl: FilterComboBox1
          F i l t e r C o m b o B o x 1 FileList: FileListBox1
          ????? Filter: 所有文件 ( * . * ) | * . * |文本文件( * . t x t ) | * . t x t
          L a b e l 5 路徑名:
          L a b e l 6 C : \ S a m p l e s \ S 0 6 B
          L a b e l 7 文件名( & N ) : FocusControl: Edit1
          E d i t 1
          B u t t o n 1 文件長度( & L ) . . . Te x t : * . *
          #include<stdio.h>
          void __fastcall TForm1::Button1Click(TObject *Sender)
          {
          FILE* fp;
          AnsiString FileFullName;
          long size;
          AnsiString PropertyMes;
          FileFullName=Label2->Caption+"\\"+Edit1->Text;
          if(FileExists(FileFullName))
          {
          ? fp=fopen(FileFullName.c_str(),"rt");
          ? if(fp!=NULL)
          ? {
          ??? fseek(fp,0L,SEEK_END);
          ??? size=ftell(fp);//get the length of file
          ??? PropertyMes="file is total"+IntToStr(size)+"bytes.";
          ??? MessageDlg(PropertyMes,mtInformation,TMsgDlgButtons() << mbOK, 0);

          ? }else
          ? {
          ????? MessageDlg(PropertyMes,mtWarning,TMsgDlgButtons() << mbOK, 0);
          ? }
          ? fclose(fp);
          ?}
          }

          ?2 獲取驅動器類型信息
          ?UINT GetDriveType(
          ? LPCTSTR lpRootPathName //獲取根目錄的路徑名稱
          ?)
          ?
          表6-5?? 函數G e t D r i v e Ty p e的返回值及其含義
          數 值???????????????????????????? 含 義
          0??????????????????????????? 無法檢測驅動器的類型
          1???????????????????????????? 根目錄不存在
          D R I V E _ R E M O VA B L E 可移動驅動器
          D R I V E _ F I X E D 不可移動驅動器
          D R I V E _ R E M O T E 網絡驅動器
          D R I V E _ C D R O M C D - R O M驅動器
          D R I V E _ R A M D I S K 虛擬驅動器

          Result=GetDriveType(Edit2->Text.c_str());
          3 操作ini 文件

          posted @ 2006-09-09 23:25 康文 閱讀(2970) | 評論 (0)編輯 收藏

          <2006年9月>
          272829303112
          3456789
          10111213141516
          17181920212223
          24252627282930
          1234567

          導航

          統計

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 保靖县| 偏关县| 乐都县| 黄平县| 鹤山市| 西乌| 武强县| 手游| 杭锦后旗| 乐安县| 宝坻区| 沂水县| 启东市| 建水县| 泉州市| 惠水县| 慈溪市| 独山县| 体育| 桂平市| 开原市| 上杭县| 六枝特区| 观塘区| 双江| 资溪县| 南城县| 舞阳县| 博爱县| 惠州市| 墨竹工卡县| 湘乡市| 大姚县| 嘉祥县| 满洲里市| 湾仔区| 苍梧县| 荥阳市| 阿拉善右旗| 广丰县| 南投市|