如何在C#2.0中处理SQL Query CommandTimeout

时间:2012-03-02 10:47:27

标签: c#-2.0 sqlcommand command-timeout

我在c#中有以下代码。

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 个答案:

答案 0 :(得分: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
       }
    }

只是一个例子..