Free Blog Counter

Ranjiths Dot Net Blog: Connecting to a Database

Friday, 22 August 2008

Connecting to a Database

The first step to using ADO.NET is to connect to a data source, such as a database. Using the Connection object, you tell ADO.NET which database you want to connect. The Connection object is your gateway to the database, and all the operations you perform against the database must go through this gateway.

Now lets try by a creating a connection to the Northwind database.

‘Namespace

Imports system.data

Imports system.data.sqlclient

Dim connNorthwind as new SqlConnection

connNorthwind.ConnectionString=“data source = (local) ; initial catalog=Northwind; integrated security=SSPI;”

‘Some of the names in the connection string also go by aliases. You can use Server instead of data source to specify your SQL Server. Instead of initial catalog, you can specify database.

The Open() Method

After you have specified the ConnectionString property of the Connection object, you must call the Open() method to establish a connection to the database.

connNorthwind.Open()

The Close() Method

Use the Connection object’s Close() method to close an open connection.

connNorthwind.Close()

Alternatively, you could call the Dispose() method, which also closes the connection:

ConnNorthwind.Dispose()


The final code for the Connection will look like this:

Imports system.data

Imports system.data.sqlclient

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Button1.Click

Dim connNorthwind As New SqlConnection

connNorthwind.ConnectionString = "data source=(local); initial

catalog=Northwind; integrated security=SSPI;"

connNorthwind.Open()

'some code here…….

connNorthwind.close()

End Sub

End Class

No comments: