Archive

Archive for August, 2009

ASP.Net – How to update database data using VB.Net

August 1, 2009 Leave a comment

In my previous post on how to insert a new data into the database, now let’s take a look at how to update/edit the data that has been written into the database earlier. Below is a simple code to update data from database.

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

‘declare the connection string
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)

‘declare update SQL statement
Dim updatequery As String = "UPDATE <<TABLE>> SET company=@company,address=@address"

‘declare sqlcommand
Dim update As New SqlCommand(updatequery, myconn)

‘using WITH loop function to loop the data from textbox
With update.Parameters
    .Add(New SqlParameter("@company", txtncompany.Text.ToString.Trim))
    .Add(New SqlParameter("@address", txtaddress.Text.ToString.Trim))
End With

‘open connection to database
myconn.Open()

‘execute the query
renew.ExecuteNonQuery()

‘close the connection
myconn.Close()

Advertisements
Categories: ASP.NET

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

August 1, 2009 Leave a comment

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.

Categories: ASP.NET