希望从用户定义的sql server获取可用数据库列表。下面的代码正确查询可用的服务器,但现在我正在尝试在所选服务器上查找可用的数据库。
思想?
Dim dt As Data.DataTable = Nothing, dr As Data.DataRow = Nothing
dt = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources()
For Each dr In dt.Rows
cbAvailableSQLServers.Items.Add(dr.Item(0).ToString)
Next
答案 0 :(得分:1)
首先,您的代码将获得默认实例,但不会显示命名实例的名称。以下是我过去使用SQL Server实例填充ComboBox
的方法:
Private Sub serverCombo_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles serverCombo.DropDown
If Me.populateServerList Then
'Enumerate available SQL Server instances.'
Dim serverTable As DataTable = SqlDataSourceEnumerator.Instance.GetDataSources()
Dim upperBound As Integer = serverTable.Rows.Count - 1
Dim serverNames(upperBound) As String
For index As Integer = 0 To upperBound
If serverTable.Rows(index).IsNull("InstanceName") Then
serverNames(index) = CStr(serverTable.Rows(index)("ServerName"))
Else
serverNames(index) = String.Format("{0}\{1}", _
serverTable.Rows(index)("ServerName"), _
serverTable.Rows(index)("InstanceName"))
End If
Next
Dim currentServerName As String = Me.serverCombo.Text
With Me.serverCombo
.BeginUpdate()
.Items.Clear()
.Items.AddRange(serverNames)
.SelectedItem = currentServerName
.Text = currentServerName
.EndUpdate()
End With
Me.populateServerList = False
End If
End Sub
以下是我在同一个应用程序中填充服务器的数据库列表的方法:
Private Sub databaseCombo_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles databaseCombo.DropDown
Using connection As New SqlConnection(Me.GetConnectionString(False))
Try
connection.Open()
'Enumerate available databases.'
Me.databaseCombo.DataSource = connection.GetSchema("Databases")
Catch
MessageBox.Show("Unable to connect.", _
"Connection Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Try
End Using
End Sub
Private Function GetConnectionString(ByVal includeDatabase As Boolean) As String
Dim builder As New SqlConnectionStringBuilder()
'Build a connection string from the user input.'
builder.DataSource = Me.serverCombo.Text
builder.IntegratedSecurity = Me.integratedSecurityOption.Checked
builder.UserID = Me.userText.Text
builder.Password = Me.passwordText.Text
If includeDatabase Then
builder.InitialCatalog = Me.databaseCombo.Text
End If
Return builder.ConnectionString
End Function
答案 1 :(得分:0)
您可以查询sys.databases以获取特定服务器实例的数据库列表,也可以使用Microsoft.SqlServer.Management.Smo命名空间以编程方式查询它们