我需要确定连接字符串连接C#控制台应用程序(.NET 2.0)的SQL Server版本(在此特定情况下为2000,2005或2008)。任何人都可以就此提供任何指导吗?
谢谢,MagicAndi
更新
如果可能的话,我希望能够从ADO.NET连接对象中确定SQL Server版本。
答案 0 :(得分:17)
此代码将确定正在使用的SQL Server数据库的版本 - 2000,2005或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's回答:
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();
}
答案 1 :(得分:12)
SqlConnection con = new SqlConnection("Server=localhost;Database=test;user=admin;password=123456;");
con.Open();
Text = con.ServerVersion;
con.Close();
con.ServerVersion 会给你:
答案 2 :(得分:7)
从正常的SqlCommand运行此脚本 - 它非常广泛且有用!
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Patch Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
马克
答案 3 :(得分:6)
答案 4 :(得分:2)
Server版本也可用作Connection对象上的(字符串)属性,也可用作ServerConnection上的SqlVersion属性。
SQl2008版本> = 10