How to add data to database using VB.NET

Tuesday, 24 March 2009 12:13 by scngan

How to add data to database using VB.NET ? Below will be a simple code that can help you.

' import the class library
Imports System.Data.SqlClient

'Declare the connection string
Dim strConn As String = "Data Source=.\SQLExpress;integrated security=true;attachdbfilename=|DataDirectory|\StudentDB.mdf;user instance=true;"
'declare the connection
Dim myconn As New SqlConnection(strConn)

' insert data into database
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()

Make sure you close your connection everytime after you open it.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   , ,
Categories:   Technical Stuff
Actions:   | E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed
Comments are closed