从 ADO.NET 确定 SQL Server 的版本 [英] Determine version of SQL Server from ADO.NET

查看:35
本文介绍了从 ADO.NET 确定 SQL Server 的版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定连接字符串连接 C# 控制台应用程序 (.NET 2.0) 的 SQL Server 版本(在本例中为 2000、2005 或 2008).任何人都可以提供任何指导吗?

I need to determine the version of SQL Server (2000, 2005 or 2008 in this particular case) that a connection string connects a C# console application (.NET 2.0). Can anyone provide any guidance on this?

谢谢,MagicAndi

Thanks, MagicAndi

更新

如果可能,我希望能够从 ADO.NET 连接对象中确定 SQL Server 版本.

I would like to be able to determine the SQL Server version form the ADO.NET connection object if possible.

推荐答案

此代码将确定正在使用的 SQL Server 数据库的版本 - 2000、2005 或 2008:

This code will determine the version of SQL Server database being used - 2000, 2005 or 2008:

try
{
    SqlConnection sqlConnection = new SqlConnection(connectionString);
    Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection));

    switch (server.Information.Version.Major)
    {
      case 8:
        MessageBox.Show("SQL Server 2000");
        break;
      case 9:
        MessageBox.Show("SQL Server 2005");
        break;
      case 10:
        MessageBox.Show("SQL Server 2008");
                break;
      default:
        MessageBox.Show(string.Format("SQL Server {0}", server.Information.Version.Major.ToString())); 
        break;   
    }
}
catch (Microsoft.SqlServer.Management.Common.ConnectionFailureException)
{
    MessageBox.Show("Unable to connect to server",
        "Invalid Server", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

下面的代码也会这样做,这次使用 NinthSense 的答案:

The code below will do the same, this time using NinthSense's answer:

try
{       
    SqlConnection sqlConnection = new SqlConnection(connectionString);
    sqlConnection.Open();

    string serverVersion = sqlConnection.ServerVersion;
    string[] serverVersionDetails = serverVersion.Split( new string[] {"."}, StringSplitOptions.None);

    int versionNumber = int.Parse(serverVersionDetails[0]);

    switch (versionNumber)
    {
        case 8:
            MessageBox.Show("SQL Server 2000");
            break;
        case 9:
            MessageBox.Show("SQL Server 2005");
            break;
        case 10:
            MessageBox.Show("SQL Server 2008");
            break;
        default:
            MessageBox.Show(string.Format("SQL Server {0}", versionNumber.ToString()));  
            break;  
    }
}
catch (Exception ex)
{
    MessageBox.Show(string.Format("Unable to connect to server due to exception: {1}", ex.Message),
        "Invalid Connection!", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
finally
{
    sqlConnection.Close();
}

这篇关于从 ADO.NET 确定 SQL Server 的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆