65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 SMO 进行 SQL Server 身份验证

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.42/5 (9投票s)

2008 年 12 月 17 日

CPOL

2分钟阅读

viewsIcon

64576

downloadIcon

2089

通过允许用户选择服务器和数据库来设置连接字符串。

DBConnectionMgr.JPG

引言

在本文中,我将介绍如何通过允许用户选择服务器和实例以及数据库来生成连接字符串。用户还可以选择身份验证类型。它的工作方式与 SQL Server 允许用户连接到数据库的方式相同。

这是一个简单的应用程序,使用 SMO - SQL Server Management Objects。

背景

好的,现在我假设你具备基本的 C# 知识(复选框和下拉列表)。此外,我在此项目中使用了 Application_Idle 事件和 EventHandler ,因此你首先需要阅读相关资料。

工作

我使用了两个对象

  1. Microsoft.SqlServer.Management.Common.ServerConnection 
    	ServerConnection m_ServerConnection;
  2. Microsoft.SqlServer.Management.Smo.Server Server m_Server;

对于上述对象,名为 Microsoft.SqlServer.Smo.dllMicrosoft.SqlServer.ConnectionInfo.dll 的 DLL 应该位于 SQL Server 目录中(Program Files\Microsoft SQL Server\90\SDK\Assemblies)。 确保它们在那里,否则你将需要下载这些 DLL 并将其包含在引用中。

首先,我已经在 Properties.Settings 中声明了所有全局变量。 你可以通过在 Visual Studio IDE 中打开 Settings.settings 文件来直接访问它们。 其中有一个名为 BackupConnectionString 的变量,它应该保存默认连接字符串。 如果你愿意,可以将其排除。

现在,我们需要首先填充网络上可能存在的服务器列表。 这在 Application_Idle 事件中完成。 然后我们将该列表用作 DataSource ,以显示可用服务器列表的下拉框。 用户还应该能够键入服务器名称,如果他们不想从可用服务器中选择的话

DataTable dtServers = SmoApplication.EnumAvailableSqlServers(false);
dtServers.PrimaryKey = new DataColumn[] { dtServers.Columns[0] };
this.cmbServerName.DataSource = dtServers;

然后我们需要检查用户选择的所有选项,例如身份验证模式等。 基于此,我们更改连接字符串。

用户现在已经选择了服务器和实例以及所有身份验证详细信息。 我们现在需要在用户单击“测试连接”按钮或单击数据库下拉框时显示驻留在该服务器上的所有数据库。 但是,我们忽略系统数据库。

我编写了一个 ConnectDatabase 方法来测试连接

if (!string.IsNullOrEmpty(this.cmbServerName.Text))
{
	this.m_ServerConnection = 
		new ServerConnection(this.cmbServerName.Text.ToString());
      //First check type of Authentication
      if (this.rdbWindowsAuthentication.Checked == true)   //Windows Authentication
      {
      	this.m_ServerConnection.LoginSecure = true;
            this.m_Server = new Server(this.m_ServerConnection);
      }
      else
      {
      	// Create a new connection to the selected server name
		this.m_ServerConnection.LoginSecure = false;
      	this.m_ServerConnection.Login = this.txtUserName.Text;       //Login User
	//Login Password
         this.m_ServerConnection.Password = this.txtPassword.Text;    
	this.m_ServerConnection.DatabaseName = this.cmbDbName.Text;  //Database Name
      	// Create a new SQL Server object using the connection we created
      	this.m_Server = new Server(this.m_ServerConnection);
      }
	return true;
}
return false;

要将数据库名称添加到下拉框

this.cmbDbName.Items.Clear();
// Loop through the databases list
foreach (Database db in this.m_Server.Databases)
{
      //We don't want to be adding the System databases to our list
      //Check if database is system database
      if (!db.IsSystemObject) 
      {
 	     this.cmbDbName.Items.Add(db.Name); // Add database to combobox
      }
}
this.cmbDbName.SelectedIndex = 0;

当用户按下“确定”按钮时,我将所有值添加到在 Properties.Settings 中声明的全局变量中。

历史

  • 2008 年 12 月 17 日:初始发布
© . All rights reserved.