0

我在 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; ,现在我想给用户一个错误消息,如果超时时间超过这个,或者你可以说数据库已关闭。

请推荐!!

4

1 回答 1

1

请参阅 如何捕获 SQLServer 超时异常

问题已经回答了。。

为了改进编码,您可以使用

    尝试{

         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) {
        //将您的消息返回给控件或显示错误
       }
    }

well just an example..

于 2012-03-02T11:33:03.283 回答