VB2010: Connect to SQL Server 2008

左心房为你撑大大i 提交于 2020-01-05 08:41:44

问题


I have a database on SQL Server 2008 and am trying to run code on Visual Basic 2010 to connect to it. I have the following code but am getting the error A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) on the line SQLConn.Open():

Imports System.Data
Imports System.Data.SqlClient

Public Class Form1

    Dim SQLConn As SqlClient.SqlConnection

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim i As Integer
        Dim connectionstring As String
        connectionstring = "Data Source=MySQLServer\MyInstance;Database=MyDatabase;Integrated Security=true;"

        Try
            SQLConn = New SqlConnection(connectionstring)
            SQLConn.Open()
        Catch ex As Exception
            MsgBox(ex.Message & " Error Connecting to database!", MsgBoxStyle.Critical)
            Exit Sub
        End Try
        Dim da As SqlDataAdapter
        da = New SqlDataAdapter("SELECT * from DR_Users", SQLConn)
        Dim dt As DataTable
        da.Fill(dt)
        For i = 0 To dt.Rows.Count - 1
            Dim dr As DataRow = dt.Rows(i)
            Debug.Print(dr.Item("UserId").ToString)
        Next

    End Sub
End Class

Edit: I have been working on VBA code and know the server\instance and database names are correct. Not sure why it's not working under VB.NET 2010.


回答1:


first step is to install "SQL Server management studio". If you can connect to your sql server with it, the nyou know that the server is accessible. otherwise you need to fix firewall, start sql server, etc...

About the connection string: I prefer to "build" it on-the-fly, maybe that works for you, too

  Public Property ServerName() As String
  Public Property DatabaseName() As String
  Public Property Login() As String
  Public Property Password() As String

  Private Function SqlConn(Optional timeout As Integer = 0) As String
    ' Initialize the connection string builder for the 
    ' underlying provider. 
    Dim sqlBuilder As New SqlClient.SqlConnectionStringBuilder()

    ' Set the properties for the data source. 
    sqlBuilder.DataSource = _serverName
    sqlBuilder.InitialCatalog = _databaseName
    sqlBuilder.IntegratedSecurity = False
    sqlBuilder.MultipleActiveResultSets = True 'to avoid exception if a query uses anothe rquery internal

    sqlBuilder.UserID = _Login
    sqlBuilder.Password = _Password
    If timeout > 0 Then
      sqlBuilder.ConnectTimeout = timeout
    End If

    Return sqlBuilder.ToString
  End Function

so you can write

Using sqlConn As New SqlClient.SqlConnection(sqlConnString)
  sqlConn.Open()
      [...]
  sqlConn.Close()
End Using

for server name, use the name that worked to connect to with Server Management Studio, same with Login and Password. Database = the one you can see when connected.

And if you use Windows credential, you can keep usign IntegratedSecurity. But I guess for programs it makes more sense to be a bit more independent, so just setup a normal sql login.




回答2:


Possible causes:

1) The name of the database server is not MySQLServer. If it is your local machine, change this to . or (local) or the name of your machine.

2) Either SQL Server is not running in an instance or the instance is not named MyInstance.

3) The SQL Server service is not actually running. Try starting it.

4) SQL Server is separated from the machine you are running this code on by a firewall which is not letting the SQL traffic through.

Update:

5) The local SQL Server Client Network Utility either is not configured to support the protocols that SQL Server does or has an old alias that points to the wrong machine or address. To open this utility, you can run cliconfg from the Run... prompt or the command line.

Update 2:

This blog entry has an excellent explanation of exactly how to troubleshoot this specific issue.



来源:https://stackoverflow.com/questions/8017845/vb2010-connect-to-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!