Sqlconnection为什么尝试catch需要消息

时间:2014-01-23 17:39:37

标签: c# sql-server visual-studio-2010

我有这个类打开一个连接。

 public static SqlConnection GetConnection()
    {
        string str3 = "Data Source= 10.161.2.110 ;Initial Catalog =eplo;uid =sa;pwd = tudo";
        SqlConnection abre3 = new SqlConnection(str3);
        abre3.Open();
        return abre3;
    }

工作正常,但是当无法连接时我需要一些东西来返回显示连接不可能的消息

我很晚才打电话给这个班级:

private SqlConnection interna = Tconex.GetConnection();

2 个答案:

答案 0 :(得分:0)

private SqlConnection interna;

try
{
    interna = Tconex.GetConnection();
}
catch (Exception ex)
{
    Console.Writeline("Failed to connect: ", ex.Message);
}

如果由我决定,我会创建一个数据库包装器:

public class GhettoDbWrapper
{
    string connectionString;

    public GhettoDbWrapper(string serverInstanceName, string databaseName)
    {
        // Create connection string
    }

    public ExecuteGhettoDb(string query)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionSting))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(query, connection);
                command.ExecuteNonQuery();
            }
        }
        catch (SqlException ex)
        {
            throw new Exception("Connection failed: ", ex.Exception);
        }
        catch (Exception ex)
        {
            // Ghetto throw the rest of them
            throw;
        }
    }
}

答案 1 :(得分:0)

将您的连接类包装在重新抛出SqlException的try / catch中:

private const string SQL_CONN_STR = "Data Source= 10.161.2.110 ;Initial Catalog =eplo;uid =sa;pwd = tudo";

public static SqlConnection GetConnection() {
  try {
    return new SqlConnection(SQL_CONN_STR);
  } catch (SqlException err) {
    throw new Exception("The connection is not possible.", err);
  }
}

现在,在您的表单或调用此静态方法的其他代码中,将其包装在显示错误的try / catch例程中:

// in your code:
private void Connect() {
  SqlConnection conn = null;
  try {
    conn = GetConnection();
  } catch (Exception err) {
    MessageBox.Show(this, err.Message, "Connection Error", MessageBoxButtons.OK);
  }
  if (conn != null) {
    // more code
  }
}

此外,如果您想记录或检查基础 SqlException ,您可以添加一些内容来检查 InnerException

  Console.WriteLine("Connection SqlError: " + err.InnerException.Message);