How to Connect to SQL Server Through VB.net
- 1). Click the Windows "Start" button and select "All Programs." Click "Microsoft .NET Framework," then click "Visual Studio" to open the software.
- 2). Open your project file to load all of the code. Double-click the form you want to use to connect to the server.
- 3). Add the ADO libraries to the top of the code file. Copy and paste the following library files to your VB editor:
Imports System.Data
Imports System.Data.SqlClient - 4). Create the SQL Server connection using the ADO object. The following code connects to the "myserver" SQL Server:
Dim connstring As String
connstring = "server=myserver;uid=username;pwd=password;database=db;"
Dim conn As New SqlConnection(connstring)
conn.Open()
Replace the "myserver," "username," "password," and "db" values with your own server information. - 5). Query the server. After you connect to the server, you can query for database information. The following code retrieves a list of customers:
Dim command As New SqlCommand("SELECT * from customers", conn)
Dim reader As SqlDataReader = command.ExecuteReader() - 6). Close the connection. After you complete querying the server, close the connection using the following code:
conn.Close
Source...