O'Reilly logo

Programming Visual Basic .NET by Dave Grundgeiger

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Connecting to a SQL Server Database

To read and write information to and from a SQL Server database, it is necessary first to establish a connection to the database. This is done with the SqlConnection object, found in the System.Data.SqlClient namespace. Here’s an example:

' Open a database connection.
Dim strConnection As String = _
   "Data Source=localhost;Initial Catalog=Northwind;" _
   & "Integrated Security=True"
Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open(  )

This code fragment instantiates an object of type SqlConnection, passing its constructor a connection string. Calling the SqlConnection object’s Open method opens the connection. A connection must be open for data to be read or written, or for commands to be executed. When you’re finished accessing the database, use the Close method to close the connection:

' Close the database connection.
cn.Close(  )

The connection string argument to the SqlConnection class’s constructor provides information that allows the SqlConnection object to find the SQL Server database. The connection string shown in the earlier code fragment indicates that the database is located on the same machine that is running the code snippet (Data Source=localhost), that the database name is Northwind (Initial Catalog=Northwind), and that the user ID that should be used for logging in to SQL Server is the current Windows login account (Integrated Security=True). Table 8-1 shows the valid SQL Server connection string settings.

Table 8-1.  ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required