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

如何在网络中枚举 SQL Server 实例

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.96/5 (9投票s)

2013年2月11日

CPOL
viewsIcon

63047

downloadIcon

2567

这个技巧适用于想要列出网络中所有可用 SQL Server 实例的用户。

引言

有时我们需要列出局域网中所有可用的 SQL Server 实例,以便获取有关它们的信息。例如,当我们需要为数据库编写自定义安装程序时,这会很有用。

这个技巧向我们展示了如何解决这个问题。

使用代码

代码尽可能简单 Wink | ;)

测试代码需要什么?

  1. 创建一个新项目(Windows 应用程序),
  2. 添加:
    • 1 个 Label
    • 1 个 ComboBox(将其名称更改为:CmbSQLInstance
    • 1 个 DataGridView(将其名称更改为:DGVSQLInstances

在开始编码之前,您需要设置对 System.Data.Sql 命名空间的引用(如这里所述:http://msdn.microsoft.com/en-us/library/vstudio/wkze6zky%28v=vs.80%29.aspx)。

'declare variables
Dim dt As Data.DataTable = Nothing, dr As Data.DataRow = Nothing

Try
    'get sql server instances in to DataTable object
    dt = Sql.SqlDataSourceEnumerator.Instance.GetDataSources()

    'load data in to ComboBox
    For Each dr In dt.Rows
        Me.CmbSQLInstance.Items.Add(dr.Item(0).ToString)
    Next
    'load data in to DataGridView
    Me.DGVSQLInstances.DataSource = dt

Catch ex As System.Data.SqlClient.SqlException
    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error!")

Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error!")

Finally
    'clean up ;)
    dr = Nothing
    dt = Nothing
End Try 

替代方案

历史

  • 2013/02/11 - 首次版本。
  • 2013/02/13 - 添加了源代码文件
© . All rights reserved.