SQL Server的超时设置
我正在使用VSTS 2008 + ADO.Net + C#+。Net 3.5 + SQL Server 2008.我在客户端使用ADO.Net连接到数据库服务器以执行存储过程,然后从存储过程返回结果。
这是我的代码。 我有两个关于超时的问题,
-
如果我没有明确设置任何超时相关设置,对于与数据库服务器的连接,是否有任何超时设置(例如,如果在一段默认时间内无法连接到数据库服务器,会有一些超时exception?)?
-
如果我没有明确设置任何超时相关设置,对于执行存储过程,是否有任何超时设置(例如,如果无法从服务器检索到ADO.Net客户端的结果一段默认时间,则会有一些超时例外?)?
using (SqlConnection currentConnection = new SqlConnection("Data Source=.;Initial Catalog=TestDB;Trusted_Connection=true;Asynchronous Processing=true")) { // check current batch conut currentConnection.Open(); using (SqlCommand RetrieveOrderCommand = new SqlCommand()) { RetrieveOrderCommand.Connection = currentConnection; RetrieveOrderCommand.CommandType = CommandType.StoredProcedure; RetrieveOrderCommand.CommandText = "prc_GetOrders"; RetrieveBatchCountCommand.Parameters.Add("@Count", SqlDbType.Int).Direction = ParameterDirection.Output; RetrieveBatchCountCommand.ExecuteNonQuery(); int rowCount = Convert.ToInt32(RetrieveOrderCommand.Parameters["@Count"].Value); } }
正如gbn已经提到的,有两种类型的超时:
1)连接超时:这由连接字符串控制:
Data Source=.;Initial Catalog=TestDB; Trusted_Connection=true;Asynchronous Processing=true
如果您将Connect Timeout=120
添加到此字符串,您的连接将尝试120秒打开然后中止。
Data Source=.;Initial Catalog=TestDB; Trusted_Connection=true;Asynchronous Processing=true; Connect Timeout=120;
2)命令超时:对于每个命令,您还可以指定超时 – 在取消查询之前,ADO.NET将等待该时间。 您在SqlCommand对象上指定:
using (SqlCommand RetrieveOrderCommand = new SqlCommand()) { RetrieveOrderCommand.CommandTimeout = 150; }
是的,可以设置2种超时
- 连接超时
- 命令超时
在VBA,.net等中默认为30秒
在sqlconnection
类中,有一个名称为ConnectionTimeout
的属性。
这不能直接用于设置所需的连接超时值,因为它是只读的,即只实现了“get”并且没有在此属性上实现“set”。所以我们必须在连接字符串本身和集合中使用关键字“Connection Timeout”期望值。
EXI:
Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI;Connection Timeout=30";(30 means 30 seconds)
30秒是建立与服务器连接的最长时间(如172.160.0.2
或类似ADMINISTRATOR\SQLEXPRESS
)。如果它无法立即建立与服务器的连接,那么它将尝试最多30秒。
如果服务器有效且能够连接到服务器并且数据库名称或登录凭据无效,则此超时将不适用。它会立即抛出无效凭据或数据库的exception
上述就是C#学习教程:SQL Server的超时设置分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/988079.html