2011-02-08 57 views
1

我嘗試寫一個簡單的GUI形式顯示,如果任何數據庫連接我的應用需求是unavilable檢查開放的Oracle連接

public void tryConnection(List<String> connections, List<String> databaseNames) 
    { 
     tableLayoutPanel1.RowCount = connections.Count(); 
     Label label; 
     Label sucOrFail; 
     String message = ""; 

     int row = 0; 
     for (int i = 0; i < connections.Count(); i++) 
     { 
      try 
      { 
       label = new Label(); 
       sucOrFail = new Label(); 
       label.AutoSize = true; 
       sucOrFail.AutoSize = true; 
       label.Text = databaseNames[i].ToUpper(); 
       tableLayoutPanel1.Controls.Add(label, 0, row); 
       OracleConnection con = new OracleConnection(connections[i]); 
       con.Open(); 

       message = "Success, You Managed to connect to " + databaseNames[i]; 
       sucOrFail.Text = message; 
       sucOrFail.ForeColor = System.Drawing.Color.LawnGreen; 
       tableLayoutPanel1.Controls.Add(sucOrFail, 1, row); 
       con.Close(); 
       row++; 
      } 
      catch (OracleException e) 
      { 
       Console.WriteLine("failure"); 
      } 
     } 

有反正我可以修改本,這樣,如果con.open()失敗它不會跳入捕捉,因爲當這種情況發生時,我放鬆了我在循環中的位置,並且無法繼續,因爲我需要。

例如

if (con.open()) 
{ 
    message = ...... 
} 
else 
{ 
    message = ..... 
} 

回答

1

爲什麼不使用內部的try/catch內循環:

for (int i = 0; i < connections.Count(); i++) 
{ 
    try { 
     con.Open(); 
     // connection ok 
    } 
    catch (OracleException e) { 
     // couldn't connect 
    } 
} 
+0

感謝您的幫助 – tom 2011-02-08 16:23:04

0

你應該有專門圍繞con.Open try catch塊()。

+0

感謝您的幫助 – tom 2011-02-08 16:24:49