如何从C#WinForms应用程序判断SQL Server自动升级是否成功

本文关键字:成功 是否 Server SQL C#WinForms 应用程序 判断 | 更新日期: 2023-09-27 18:19:57

我正在通过用于升级我们的应用程序的WinForms应用程序自动将SQL Server 2005 Express升级到SQL Server 2008R2 Express。该应用程序部署在大约800多个位置,因此我们不需要任何手动步骤。

我已经编写了以下代码,主要用于执行升级。我需要知道,确定SQL Server安装程序是否成功完成的最佳做法是什么?我应该只为该进程查找0的退出代码吗?这足够好吗;即,如果升级出现问题并被回滚,它是否仍能以代码0退出(我会测试这个,但不知道模拟失败的最佳方法)?

有没有其他方法可以确定我的C#应用程序中的升级是否成功,这样我就可以在SQL Server安装程序遇到任何错误时正确处理它?

try
{
    //First, find the version of the currently installed SQL Server Instance
    string sqlString = "SELECT SUBSTRING(CONVERT(VARCHAR, SERVERPROPERTY('productversion')), 0, 5)";
    string sqlInstanceVersion = string.Empty;                
    using (DbCommand cmd = _database.GetSqlStringCommand(sqlString))
    {
        sqlInstanceVersion = cmd.ExecuteScalar().ToString();
    }
    if (sqlInstanceVersion.Equals(String.Empty))
    {
        //TODO throw an exception or do something else
    }
    //11.00 = SQL2012, 10.50 = SQL2008R2, 10.00 = SQL2008, 9.00 = SQL2005, 8.00 = SQL2000
    switch (sqlInstanceVersion)
    {
        case "11.00":
        case "10.50":
        case "10.00":
            //Log that the version is already up to date and return
            return;
        case "9.00":
        case "8.00":
            //We are on SQL 2000 or 2005, so continue with upgrade to 2008R2
            break;
        default:
            //TODO throw an exception for unsupported SQL Server version
            break;
    }
    string upgradeArgumentString = "/Q /ACTION=upgrade /INSTANCENAME={0} /ENU /IACCEPTSQLSERVERLICENSETERMS";
    string instanceName = "YourInstanceNameHere";
    string installerFilePath = AppDomain.CurrentDomain.BaseDirectory + "''SQLEXPR_x86_ENU.exe"; 
    if (!File.Exists(installerFilePath))
    {
        throw new FileNotFoundException(string.Format("Unable to find installer file: {0}", installerFilePath));
    }
    Process process = new Process
    {
        StartInfo = { FileName = installerFilePath, Arguments = String.Format(upgradeArgumentString, instanceName), UseShellExecute = false }
    };
    process.Start();
    if (process.WaitForExit(SQLSERVER_UPGRADE_TIMEOUT))
    {
        //Do something here when the process completes within timeout.
        //What should I do here to determine if the SQL Server Installer completed successfully?  Look at just the exit code?
    }
    else
    {
        //The process exceeded timeout.  Do something about it; like throw exception, or whatever
    }
}
catch(Exception ex)
{
    //Handle your exceptions here
}

如何从C#WinForms应用程序判断SQL Server自动升级是否成功

查看完整的版本字符串,只需去掉其中的前5个字符。成功升级将更改版本字符串。