2014-01-23 27 views
0

我有这个类打开一个连接。Sqlconnection为什么试着抓住需要的消息

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(); 
+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; 
     } 
    } 
} 
0

环绕你连接类在一个try/catch是重新抛出的SQLException:

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);