ASP.Net Connect to SQL Database

Updated on 13 Feb 2008, Published on 13 Feb 2008

In ASP.Net 2.0 you can use SQLClient for creating SQL Database connection.
First you have to place the SQL connection string having authenticated username, password and name of the database as Initial Catalog and last important thing Data Source as IP/localhost defining the place of SQL Server Database server.

Apply the following in <configuration> section of web.config file:

 

<appSettings>
       <
add key="ConnectionString" value="Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=;"/>
<appSettings>

Import Namespaces for SQL Database Connection:

Imports System.Data
Imports System.Data.SqlClient

 

VB Code to connect to SQL Database:

 

' string variable to store the connection string
' defined in appsettings section of web.config file.
Dim connStr As String = ConfigurationManager.AppSettings("ConnectionString").ToString()

 

' Object created for SQL Connection
Dim myConnection As New SqlConnection(connStr)

 

' if condition that can be used to check the sql connection
' whether it is already open or not.
If myConnection.State = ConnectionState.Closed Then
myConnection.Open()
End If

 

' message string just to display the sql connection state.
Response.Write("ASP.Net 2.0 SQL Database Connection State: <b>" & myConnection.State & "</b>")

 

' if condition that can be used to check the sql connection
' if it is open then close it.
If myConnection.State = ConnectionState.Open Then
   myConnection.Close()
End If

 

1 Responses to "ASP.Net Connect to SQL Database"
Wow..thanks to share this :)
Leave a Reply

Name   (Required)


Mail   (will not be published) (Required)


Website   (http://www.example.com)




OR Subscribe via Email: