Home > ASP.NET > ASP.Net – How to add data into database using VB.Net

ASP.Net – How to add data into database using VB.Net

Past few days, 1 of my friend asked me how do we insert data into the database using ASP.Net in VB. Below is a simple code that I used to help my friend solve his problem.

‘ import the SqlClient class library
Imports System.Data.SqlClient

‘declare the connection string to the database
Dim connStr As String = "Data Source=.\SQLExpress;integrated security=true;attachdbfilename=|DataDirectory|\StudentDB.mdf;user instance=true;"

‘declare the connection
Dim myconn As New SqlConnection(connStr)

‘ insert data into database SQL statement
Dim insertcust As String = "INSERT INTO student (ID,name) VALUES (@ID,@name)"

‘declare sqlcommand
Dim insert As New SqlCommand(insertcust, myconn)

‘using WITH loop function to loop the data from textbox
With insert.Parameters
.Add(New SqlParameter("@ID", txtID.Text.Trim))
.Add(New SqlParameter("@name", txtname.Text.Trim))
End With

‘open the connection to the database
myconn.Open()

‘execute the query
insert.ExecuteNonQuery()

‘close the connection
myconn.Close()

Note: Whenever a connection to the database is opened, please remember to close the connection.

Advertisements
Categories: ASP.NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: