2010年11月28日 星期日

[SQL] join

可大致區分為inner join, left outer join, right outer join, full join, cross join
1. inner join: 只篩選出兩個table共同部份(取交集), 通常是以 WHERE... 方式, 也包含條件
2. left outer join: 以左邊 table 為主, 也就是左邊 table 的資料都要篩出來, 若右邊 table 沒有的值則為NULL 值, 寫法為 Select * from table1 Left outer join table2 on table1.FK = table2.PK
3.  right outer join:以右邊table為主, 右邊 table 的資料都要篩出來, 若左邊 table 沒有的值則為NULL 值, 寫法為 Select * from table1 Right outer join table2 on table1.FK = table2.PK
4. full join: 左右兩邊table的資料都列出來, 沒有的值為NULL
5. cross join: 列出左有兩邊資料列相乘的後的結果

2010年11月25日 星期四

[Java] try/catch note

以前都搞不懂try/catch, 最近整理了一下
1. 使用try/catch的目的是exception handling, 只捕捉try block中的異常, 而在catch block中的就是exception handler.
2. 如果沒有使用try/catch,exception仍然會產生, 不過會層層往caller丟, 並且中斷原流程.
3. 使用try/catch則表示你要處理exception, exception處理完, 原流程仍會繼續進行(除非在handler中再throw),通常很多exception都會造成程式無法在往下走, 如: SQLException, ClassNotFoundException..., 有時handler只是log下這些訊息而已.
4. 個人看法是, 要不要寫try/catch是判斷handle此exception能否讓程式流程繼續進行(可能發生此exception之後程式就無法再往下走, 也無法回傳結果), 若能則用, 若不能就不用而給caller處理.


比較能理解有人說這樣寫法catch(Exception ex){ }是危險的code, 都不處理的話catch它幹嘛?也沒往上丟, 這樣出錯很難debug
最後寫了段code來測試..

package util;

public class TryCatchTest {
    public static void main(String[] args){
        try{
            int value = compute4(true);
            System.out.println("value:"+value);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    private static int compute1(boolean state){
        int result = -1;
        try{
            if(state)
                throw new Exception("Exception happened!!");
            else
                result = 1;
        }catch(Exception e){
            //handler 的處理是印出錯誤訊息
            e.printStackTrace();
        }
        //上段code發生 exception 時仍會回傳值, caller 的主流程會繼續
        return result;
    }
   
    private static int compute2(boolean state) throws Exception{
        int result = -1;
        if(state)
            //不會回傳值, exception會丟給caller, 主流程會停止
            throw new Exception("Exception Happened!!");
        else
            result = 1;
        return result;
    }
   
    private static int compute3(boolean state) throws Exception{
        int result = -1;
        try{
            if(state)
                throw new Exception("Exception happened!!");
            else
                result = 1;
        }catch(Exception e){
            //往上丟
           e.printStackTrace();
            throw e;
        }
        return result;
    }
   
    //丟出unchecked exception
    private static int compute4(boolean state){
        int result = -1;
        if(state)
            throw new RuntimeException("Exception happened!!");
        else
            result = 1;
        return result;
    }
}