2012-03-02 20 views
0

我在c#中得到了下面的代碼。如何在C#2.0中處理SQL Query CommandTimeout

SqlConnection conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;"); 
conn.Open(); 

if (conn != null) 
{ 
    //create command 
    SqlCommand cmd = new SqlCommand("dbo.GETTridionLinkData", conn); 
    cmd.Parameters.AddWithValue("@PageID", "637518"); 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.CommandTimeout = 500; 
    StringBuilder sbXML = new StringBuilder(); 
    //Adding Root node 
    sbXML.Append("<TridionLinks>"); 

    //Reading all the values of Stored procedure return 
    using (XmlReader reader = cmd.ExecuteXmlReader()) 
    { 
     while (reader.Read()) 
     { 
      sbXML.Append(reader.ReadOuterXml().Replace("//", "/")); 
     } 
    } 

    //Closing the root node tag 
    sbXML.Append("</TridionLinks>"); 
    XmlDocument xDoc = new XmlDocument(); 

    //Loading string xml in XML Document 
    xDoc.LoadXml(sbXML.ToString()); 
} 

在上面的代碼中可以看到的是,我已經設置了cmd.CommandTimeout = 500;,現在我想給用戶一個錯誤消息,如果超時時間超過這個數或者你可以說數據庫關閉。

請建議!!

回答

1

請參考 How to catch SQLServer timeout exceptions

的問題已經有了答案..

提高編碼,您可以用

 
    try{ 

     using (sqlconnection Conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;"){ 
      ... 
     } 
    }catch(sqlException ex){ 
     if (ex.Number == -2) { 
     //return your message to the control or display the error 
     } 
    } 

也只是一個例子..

+0

感謝,我看到你發佈的鏈接,cmd.ExecuteNonQuery(); //此行將超時。那裏使用,但我使用cmd.CommandTimeout = 500;以及我使用cmd.ExecuteXmlReader()而不是cmd.ExecuteNonQuery();因此同樣的異常處理也將在這裏完成或者需要寫入其他內容 – 2012-03-02 13:04:20