在运行时更改 SqlConnection 超时
Changing SqlConnection timeout at runtime
是否可以在运行时更改数据库连接超时?据我所知唯一的办法就是修改连接字符串,然后用修改后的连接字符串创建一个新的连接实例(替换字符串的timeout属性)。
<add name="MyConnection" connectionString="Data Source=.\SQL2016;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=DbUser;Password=DbPassword;Connection Timeout=6" providerName="System.Data.SqlClient" />
服务上的某些方法可能需要非常快才能在尝试通过 Internet 连接到数据库时失败,而其他方法可以有更多的宽限期。
是否有更简洁的方法来修改连接时间(因为数据库位于 Internet 资源上)?
注意:只对在运行时改变数据库连接时间感兴趣,知道但对更改命令执行时间不感兴趣。
亲切的问候,
斯蒂芬
更新
styx 和 Zohar Peled 提供的答案更符合我的要求,特别是利用 SqlConnectiongStringBuilder class 在运行时创建连接实例之前修改连接超时.
Some methods on a service may need to be super fast to fail, and others can have more grace periods.
我假设您想将查询所需的时间 CommandTimeout 更改为 运行。
ConnectionTimeout
是您的应用程序与 sql 服务器建立连接所需的时间。对于每个方法/调用/查询,这一次等于。
using (SqlConnection sqlConnection = new SqlConnection(connstring))
{
using (SqlCommand sqlCommand = new SqlCommand("SELECT * FROM FOO", sqlConnection))
{
sqlCommand.CommandTimeout = 60; //seconds here!
你也可以改变 connstring
本身(可能有点矫枉过正)
string constring = "Data Source=.\SQL2016;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=DbUser;Password=DbPassword;Connection Timeout=6\" providerName=\"System.Data.SqlClient";
int index = constring.IndexOf("Connection Timeout=");
var oldTimeOut = new String(constring.Substring(index).Split('=')[1].Where(Char.IsDigit).ToArray());
constring = constring.Replace("Connection Timeout="+oldTimeOut, "Connection Timeout=" + newTimeOut);
是否可以在运行时更改数据库连接超时?据我所知唯一的办法就是修改连接字符串,然后用修改后的连接字符串创建一个新的连接实例(替换字符串的timeout属性)。
<add name="MyConnection" connectionString="Data Source=.\SQL2016;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=DbUser;Password=DbPassword;Connection Timeout=6" providerName="System.Data.SqlClient" />
服务上的某些方法可能需要非常快才能在尝试通过 Internet 连接到数据库时失败,而其他方法可以有更多的宽限期。
是否有更简洁的方法来修改连接时间(因为数据库位于 Internet 资源上)?
注意:只对在运行时改变数据库连接时间感兴趣,知道但对更改命令执行时间不感兴趣。
亲切的问候,
斯蒂芬
更新
styx 和 Zohar Peled 提供的答案更符合我的要求,特别是利用 SqlConnectiongStringBuilder class 在运行时创建连接实例之前修改连接超时.
Some methods on a service may need to be super fast to fail, and others can have more grace periods.
我假设您想将查询所需的时间 CommandTimeout 更改为 运行。
ConnectionTimeout
是您的应用程序与 sql 服务器建立连接所需的时间。对于每个方法/调用/查询,这一次等于。
using (SqlConnection sqlConnection = new SqlConnection(connstring))
{
using (SqlCommand sqlCommand = new SqlCommand("SELECT * FROM FOO", sqlConnection))
{
sqlCommand.CommandTimeout = 60; //seconds here!
你也可以改变 connstring
本身(可能有点矫枉过正)
string constring = "Data Source=.\SQL2016;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=DbUser;Password=DbPassword;Connection Timeout=6\" providerName=\"System.Data.SqlClient";
int index = constring.IndexOf("Connection Timeout=");
var oldTimeOut = new String(constring.Substring(index).Split('=')[1].Where(Char.IsDigit).ToArray());
constring = constring.Replace("Connection Timeout="+oldTimeOut, "Connection Timeout=" + newTimeOut);