我在SQL Server 2008上有一个数据库,我正在尝试在Visual Basic 2010上运行代码来连接它。我有以下代码,但在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)
行上收到错误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
编辑:我一直在研究VBA代码并且知道服务器\实例和数据库名称是正确的。不知道为什么它不能在VB.NET 2010下工作。
答案 0 :(得分:1)
第一步是安装“SQL Server管理工作室”。如果您可以使用它连接到您的sql server,那么您就知道该服务器是可访问的。否则你需要修复防火墙,启动sql server等...
关于连接字符串: 我喜欢在飞行中“构建”它,也许这对你有用
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
所以你可以写
Using sqlConn As New SqlClient.SqlConnection(sqlConnString)
sqlConn.Open()
[...]
sqlConn.Close()
End Using
对于服务器名称,使用与Server Management Studio连接的名称,与Login和Password相同。数据库=连接时可以看到的数据库。
如果您使用Windows凭据,则可以保持使用IntegratedSecurity。但我想对于程序而言,更加独立是更有意义的,所以只需设置正常的sql登录。
答案 1 :(得分:0)
可能的原因:
1)数据库服务器的名称不是MySQLServer。如果是本地计算机,请将其更改为。或(本地)或机器名称。
2)SQL Server未在实例中运行,或者实例未命名为MyInstance。
3)SQL Server服务实际上并未运行。尝试启动它。
4)SQL Server与运行此代码的计算机分开,防火墙不允许SQL流量通过。
<强>更新强>
5)本地SQL Server客户端网络实用程序未配置为支持SQL Server执行的协议或具有指向错误计算机或地址的旧别名。要打开此实用程序,可以从Run ...提示符或命令行运行cliconfg。
更新2:
This blog entry对如何解决此特定问题提供了很好的解释。