启动程序连接到本地数据库时出现间歇性问题

时间:2014-09-24 22:24:29

标签: c#-4.0 windows-authentication sql-server-2008r2-express

我正在编写从启动文件夹运行的应用程序,并尝试连接到本地SQLServer2008-r2数据库,作为应用程序启动过程的一部分。我连接的数据库设置为使用Windows身份验证,应用程序中的连接字符串是标准的旧连接字符串: Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True

实际建立连接的代码如下所示:

String connectionstring = "Data Source=localhost\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated   Security=True";
SqlConnection cn = new SqlConnection(connectionstring);

bool databaseUp = false;

void Start()
{
    CheckSQLService();

    for (int i = 0; i < 600; i++)
    {
        if (ConnectToDB())
        {
            Console.WriteLine("Database is up and running.");
            databaseUp = true;
        }
        else
        {
            Console.WriteLine("Database Connection Failed");

            CheckSQLService();

            Console.WriteLine("Trying again");
            Thread.Sleep(1000);
        }
    }

    if(!databaseUp)
    {
        Console.WriteLine("Database Not Connected: exited loop.");
    }
}

bool ConnectToDB()
{
    try
    {
        cn.Open();
        return true;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
        return false;
    }
}

void CheckSQLService()
{
    System.ServiceProcess.ServiceController SC = new System.ServiceProcess.ServiceController("MSSQL$SQLEXPRESS");
    Console.WriteLine(" = = = Checking SQL Service Status: = = = " 
        + "\n ServiceName : " + SC.ServiceName
        + "\n State       : " + SC.Status
        + "\n Stoppable   : " + SC.CanStop
        + "\n Pausable    : " + SC.CanPauseAndContinue
        + "\n Can Shutdown: " + SC.CanShutdown);
}

基本上我循环直到我得到一个连接,如果它失败了,我睡觉并再试一次。

大部分时间(约60%)我能够在第一次尝试时成功建立连接没有问题。有时,这需要多次尝试才能成功,应用程序会等待一段时间。我还会注意到CheckSQLService()的读出每次调用它时都会验证SQL服务是否正在运行 - 有时候它只会拒绝我的Windows凭据。

任何人都有想法为什么间歇性地发生这种情况?同样,这是Windows首次启动时运行的应用程序的一部分,因此可以理解的是有许多因素在起作用(例如,其他进程或服务未完全加载或同时启动等)。

1 个答案:

答案 0 :(得分:0)

仅仅因为SQL Server服务正在运行并不意味着它已准备好接受连接。

由于您总是能够最终连接,并且您的程序在计算机启动时运行,我强烈怀疑您有时在SQL Server完全初始化并准备好连接之前运行。

在典型的启动序列中会发生很多事情。毫无疑问,您的程序有时在SQL Server准备就绪之前运行,反之亦然。