Pages

Friday, November 21, 2008

Database connection in VB.NET

Many of the beginners doesnot have the basic idea of how to establish a database connection with Visual Studio Asp.net and SQL server.
Here is a small description of it.

(All the code is written in VB.Net)

1. When connecting to a database, first of all, you need two variables, one for connection and another for the sql commands.

Dim con As New Data.SqlClient.SqlConnection()
Dim cmd As New Data.SqlClient.SqlCommand()

2. You need a "connection" between design page and database

con.ConnectionString = "Data Source=;Initial Catalog=;Integrated Security=True"

Note: Integrated Security is used when "Windows Authentication" is used. If you use server authentication, then following code will be used

con.ConnectionString = "Data Source=;Initial Catalog=;uid=;pwd="

3. You need a command text

cmd.CommandText = ""

4. Establish a relation between command and the connection

cmd.Connection = con

5. Open the connection

con.open()

6. The actual operation is done in this step.

cmd.ExecuteNonQuery()

7. Close the connection

con.Close()


So thats it !!! You have done...
Here is an example of the above explanation :


Dim con As New Data.SqlClient.SqlConnection()
Dim cmd As New Data.SqlClient.SqlCommand()
con.ConnectionString = "Data Source=VJ\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True"
cmd.CommandText = "INSERT INTO tblAddress(UName,Street,City) VALUES(@user,@street,@city)"
con.Open()
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()

No comments: