2014-01-23 39 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);