如果失败,请重新尝试打开 SQL Server 连接 [英] Re-try to open a SQL Server connection if failed
问题描述
我有一个 C# 应用程序,它有多种方法可以连接到 SQL Server 数据库以执行查询.
I have a C# application which has several methods which connect to a SQL Server database in order to execute a query.
有时连接失败,然后程序退出.
Sometimes the connection fails and then the program exits.
数据库管理员正在查看数据库,但我必须调整程序,以便在退出之前连接失败时重试 2-3 次.
A db administrator is looking on the database nevertheless I have to adapt the program in order to retry 2-3 times when a connection fails before to exiting.
我真的不知道是谁聪明地"做到了这一点.
I don't really know who doing this "smartly".
我的连接代码:
using (SqlConnection SqlCon = new SqlConnection(myParam.SqlConnectionString))
{
SqlCon.Open();
string requeteFou = "select XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
using (SqlCommand command = new SqlCommand(requeteFou, SqlCon))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
// do job
}
}
}
}
}
由于我使用了多种方法,是否有一种简单的方法可以覆盖连接"或读取"方法,例如重试连接 3 次?
Since I use several methods, is there a simply way to overwrite the "connection" or "read" method in order to retry the connection 3 times for example ?
最好的问候
推荐答案
private static function()
{
DataTable dt = new DataTable();
string connectionString = "//your connection string";
String strQuery = //"Yourquery";
const int NumberOfRetries = 3;
var retryCount = NumberOfRetries;
var success = false;
while (!success && retryCount > 0)
{
try
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = conn;
cmd.CommandTimeout = 180;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
catch (Exception ex)
{
retryCount--;
Thread.Sleep(1000 * 60 * 15);
if (retryCount == 0)
{
//yourexception
}
}
}
}
这篇关于如果失败,请重新尝试打开 SQL Server 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!