【问题标题】:Checking for an open oracle connection检查打开的 oracle 连接
【发布时间】:2023-03-18 23:11:02
【问题描述】:

我正在尝试编写一个简单的 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 = .....
}

【问题讨论】:

    标签: c# database oracle


    【解决方案1】:

    为什么不在循环内使用内部 try/catch:

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

    【讨论】:

      【解决方案2】:

      你应该在 con.Open() 周围有专门的 try catch 块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-19
        • 1970-01-01
        • 2016-01-20
        • 2011-03-13
        • 1970-01-01
        • 2019-06-19
        相关资源
        最近更新 更多