简体   繁体   中英

Computer name is needed for “Data Source” parameter of dynamic connection string

We are going to change the connection string in Settings.vb so we don't need to worry about what it is when our app runs on a different computer other than the development computer.

Our code looks like this:

Partial Friend NotInheritable Class MySettings

    Dim strComputerName As String
    Dim strConnectionString As String

    Private Sub MySettings_SettingsLoaded(ByVal sender As Object, ByVal e As System.Configuration.SettingsLoadedEventArgs) Handles Me.SettingsLoaded

        '  strComputerName = 

        ' Build a new construction string.
        '---------------------------------
        strConnectionString = "Data Source=" & strComputerName & "\sqlexpress" & _
                              ";Integrated Security=True;User Instance=True"

        ' Change to the new connection string.
        '-------------------------------------
        Me.Item("Kemal_Business_SolutionConnectionString") = (strConnectionString)
    End Sub
End Class

Can you tell me how to obtain the computer name because we need that information to place into the "Data Source=" part of the connection string?

Update: Here is what the final coding looks like. Thanks everyone for your replies:

Partial Friend NotInheritable Class MySettings

    Dim strComputerName As String
    Dim strConnectionString As String

    Private Sub MySettings_SettingsLoaded(ByVal sender As Object, ByVal e As System.Configuration.SettingsLoadedEventArgs) Handles Me.SettingsLoaded

        strComputerName = Environment.MachineName
        'strComputerName = My.Computer.Name

        ' Build a new construction string.
        '---------------------------------
        strConnectionString = "Data Source=" & strComputerName & "\sqlexpress;" & _
                              "Initial Catalog=""Kemal Business Solution"";" & _
                              "Integrated Security=True"

        ' Change to the new connection string.
        '-------------------------------------
        Me.Item("Kemal_Business_SolutionConnectionString") = (strConnectionString)
    End Sub
End Class

或更神秘的东西。

strComputerName = Environment.MachineName

Since you're using VB.net, you've got access to the My namespace, which makes this super-easy.

strComputerName = My.Computer.Name

Job done.

You can also try any one of the following line of code. Here Data Source=.; indicates the database from the local computer

strConnectionString = "Data Source=.\sqlexpress;Integrated Security=True;User Instance=True"

--OR--

strConnectionString = "Data Source=.;Integrated Security=True;User Instance=True"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM