Thursday, March 25, 2010

VB.net Opening Connection to SQLServer

Was unable to connect from Visual Basic .NET 2008 to a SQL Server Express 2008 database using the online examples. I was getting the error "network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible"

Changing from Data Source=(local) to Data Source=.\SQLEXPRESS fixed the issue

Full example:

Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As SqlDataReader

myConnection = New SqlConnection("Data Source=.\SQLEXPRESS;User ID=youruser;Password=yourpassword;Initial Catalog=yourdatabase")

Try
myConnection.Open()

myCommand = New SqlCommand("Select * from tblRoom", myConnection)

dr = myCommand.ExecuteReader()

While dr.Read()

MessageBox.Show("Field1 " & dr(0).ToString() & " Field2 " & dr(1).ToString())

End While
dr.Close()
myConnection.Close()

Catch e As Exception
'handle errors
End Try

No comments: