【问题标题】:How to get connection string which is connected right now如何获取当前已连接的连接字符串
【发布时间】:2016-03-04 07:39:09
【问题描述】:

如何获取当前连接到数据库的连接字符串?

我可以得到所有的连接字符串,但是我怎样才能得到连接的字符串呢?

提前致谢。

【问题讨论】:

  • 你可以通过两种方式。首先是 .NET SqlConnection.ConnectionString 对象,该对象通过该对象连接到 sql。其次使用self Sql Server告诉你当前连接字符串是什么,如果你使用from sql server数据库!

标签: vb.net database-connection connection-string


【解决方案1】:

对于不使用默认连接的连接,例如.\SQLEXPRESS 以下将为您提供存储在 app.config 中的连接以及跟踪连接的方法。在表单示例中,我使用的是 ms-access,但这也适用于 sql-server。

编辑here is a fully function code example 我刚刚创建的 Microsoft 代码示例 web sute。

支持课程

Public Class ConfigItem
    Public Property Data As System.Configuration.ConnectionStringSettings
    Public Property Index As Integer
End Class
Public Class ConnectionInfo
    Public Property Name As String
    Public Property ConnectionString As String
    Public Property Index As Integer
End Class

Worker 类获取连接名称、索引和连接字符串

Imports System.Configuration
''' <summary>
''' Must add a reference to System.Configuration
''' to this project.
''' </summary>
''' <remarks></remarks>
Public Class ProjectConnections
    ''' <summary>
    ''' Storage for connections
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Items As New List(Of ConnectionInfo)
    ''' <summary>
    ''' Used to remember the current connection
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property CurrentConnectionIndex As Integer

    Private RemoveThis As String = ""
    Public Sub New()
        ' look at parent assembly as this class is in a class project used by a 
        ' forms project
        RemoveThis = Reflection.Assembly.GetEntryAssembly.GetName.Name & ".My.MySettings."
        ' get connection data into the Items propery of this class
        GetInformation()
    End Sub
    ''' <summary>
    ''' Traverse through connection strings in app.config, exclude local sql-server connection
    ''' </summary>
    ''' <remarks>
    ''' tested with ms-access, sql-server attached and server based
    ''' </remarks>
    Private Sub GetInformation()
        ConfigurationManager.ConnectionStrings.Cast(Of ConnectionStringSettings)().Select(
            Function(item, index) New ConfigItem With {.Data = item, .Index = index}).ToList _
            .ForEach(
                Sub(ConfigItem)
                    If ConfigItem.Data.Name.Contains(".") Then
                        Items.Add(
                            New ConnectionInfo With
                                {
                                    .Name = ConfigItem.Data.Name.Replace(RemoveThis, ""),
                                    .ConnectionString = ConfigItem.Data.ConnectionString,
                                    .Index = ConfigItem.Index
                                })
                    End If
                End Sub)
    End Sub
End Class

利用上述类的形式。在这种情况下,app.config 中存储了两个连接。 worker 类在表单级别实例化,因此我们可以使用它来跟踪当前的连接字符串。可选地,我们可以本地化类并使用私有整数变量来记住当前连接。在表单加载中,我选择使用哪个连接而不是默认连接,将该连接的索引存储在工作类实例中,在 ComboBox 中显示连接字符串名称,并在 DataGridView 中公开所有信息。按下一个按钮,我们在运行时更改连接,而第二个按钮显示底层连接字符串。

注意 import 语句,我将 worker 类放到了一个类项目中,所以表单项目必须有对它的引用,然后是 import 语句。

Imports ConfigurationLibrary

Public Class Form1
    Private connections As ProjectConnections = New ProjectConnections()
    Private Sub CustomersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) _
        Handles CustomersBindingNavigatorSaveItem.Click

        Me.Validate()
        Me.CustomersBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.Database1DataSet)
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' here I am loading a connection other than the default
        CustomersTableAdapter.Connection.ConnectionString = connections.Items(1).ConnectionString
        ' for keeping track later as in cmdGetConnection.Click
        connections.CurrentConnectionIndex = 1
        Me.CustomersTableAdapter.Fill(Me.Database1DataSet.Customers)
        cboConnections.DataSource = connections.Items
        cboConnections.DisplayMember = "Name"
        cboConnections.SelectedIndex = 1

        dgvInformation.AutoGenerateColumns = False
        dgvInformation.DataSource = connections.Items
        CustomersDataGridView.ExpandColumns()
        dgvInformation.ExpandColumns()
    End Sub
    Private Sub cmdSetConnection_Click(sender As Object, e As EventArgs) Handles cmdSetConnection.Click
        Dim OrdinalIndex As Integer = CType(cboConnections.SelectedItem, ConnectionInfo).Index - 1
        CustomersTableAdapter.Connection.Close()
        CustomersTableAdapter.Connection.ConnectionString = connections.Items(OrdinalIndex).ConnectionString
        CustomersTableAdapter.Connection.Open()
        CustomersTableAdapter.Fill(Me.Database1DataSet.Customers)
        cboConnections.SelectedIndex = OrdinalIndex
    End Sub

    Private Sub cmdGetConnection_Click(sender As Object, e As EventArgs) Handles cmdGetConnection.Click
        Dim sb As New System.Text.StringBuilder
        sb.AppendLine(cboConnections.Text)
        sb.AppendLine(connections.Items(connections.CurrentConnectionIndex).ConnectionString)

        MessageBox.Show(sb.ToString)
    End Sub
End Class

截图

【讨论】:

    猜你喜欢
    • 2022-12-13
    • 2016-03-02
    • 1970-01-01
    • 2021-09-24
    • 2019-01-27
    • 2017-08-17
    • 1970-01-01
    • 2021-03-10
    • 2019-04-23
    相关资源
    最近更新 更多