设置数据库查询的时间限制

时间:2014-01-14 15:22:22

标签: c# sql

我想为某个数据库查询设置时间限制。

我该怎么做?

try
{
    using (SqlConnection connection = new SqlConnection(ConString)
    {
        using (SqlCommand command = new SqlCommand())
        {
            command.CommandText = sp;

            command.CommandType = CommandType.StoredProcedure;

            command.Connection = connection;

            command.Connection.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
                string role = "";
                if (reader.Read())
                    role = reader.GetString(0);

                reader.Close();
            }
        }
    }
}
catch (Exception ex)
{
     //throw new Exception(string.Format("DBLayer failure in {0}: {1}", sp, ex.Message), ex);
}

1 个答案:

答案 0 :(得分:4)

将SqlCommand对象的CommandTimeout属性设置为所需的时间限制(以秒为单位)。

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx