我正在尝试覆盖默认的SqlConnection超时时间15秒,但收到一个错误,指出
无法分配
属性或索引器,因为它是只读的。
有什么办法可以解决这个问题吗?
using (SqlConnection connection = new SqlConnection(Database.EstimatorConnection))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
connection.ConnectionTimeout = 180; // This is not working
command.CommandText = "sproc_StoreData";
command.Parameters.AddWithValue("@TaskPlanID", order.Projects[0].TaskPlanID);
command.Parameters.AddWithValue("@AsOfDate", order.IncurDate);
command.ExecuteNonQuery();
}
}发布于 2012-04-11 23:05:13
如果您想为特定的查询提供超时,那么CommandTimeout是最好的选择。
它的用法是:
command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.发布于 2012-04-11 23:00:05
您可以在连接字符串中设置超时值,但在连接之后,它是只读的。你可以在http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx上阅读更多
正如Anil所暗示的那样,ConnectionTimeout可能不是您所需要的;它控制在建立新连接时ADO驱动程序将等待多长时间。您的用法似乎表明需要等待比平常更长的时间才能执行特定的SQL查询,在这种情况下,Anil是完全正确的;使用CommandTimeout (即R/W)来更改单个SqlCommand的预期完成时间。
发布于 2015-05-27 16:42:43
一种更简洁的方法是在xml文件中设置connectionString,例如Web.Confing(WepApplication)或App.Config(StandAloneApplication)。
<connectionStrings>
<remove name="myConn"/>
<add name="myConn" connectionString="User ID=sa;Password=XXXXX;Initial Catalog=qualitaBorri;Data Source=PC_NAME\SQLEXPRESS;Connection Timeout=60"/>
</connectionStrings>通过代码,您可以通过以下方式获得连接:
public static SqlConnection getConnection()
{
string conn = string.Empty;
conn = System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
SqlConnection aConnection = new SqlConnection(conn);
return aConnection;
}只有在创建实例时才能设置ConnectionTimeout。在创建实例时,您不能更改此值。
https://stackoverflow.com/questions/10108565
复制相似问题