我试着编写一个简单的gui表单来显示我的应用程序需要的任何数据库连接是否无法使用
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()失败它就不会跳到catch,因为当发生这种情况时我会松开我在循环中的位置并且不能继续,因为我需要。
例如
if (con.open())
{
message = ......
}
else
{
message = .....
}
答案 0 :(得分:1)
为什么不在循环中使用内部try / catch:
for (int i = 0; i < connections.Count(); i++ )
{
try {
con.Open();
// connection ok
}
catch (OracleException e) {
// couldn't connect
}
}
答案 1 :(得分:0)
你应该在con.Open()周围有专门的try catch块。