ARTICLE

Insert command in ADO.NET

Posted by Rohatash Kumar Articles | ADO.NET in VB.NET February 14, 2011
Here we see how to use ADO.net to insert the data to a SQL Server database using insert command.
Download Files:
 
Reader Level:

Here we see how to use ADO.net to insert the data to a SQL Server database using insert command. To do that we create a table in SQL Server database which has the name emp and use insert command to insert the data in database.

Creating connection object

To create a connection we pass the connection string as a parameter in connection object.

Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

Dim con As New SqlConnection(str)

 

The above string defines the connection string which is used to connect the database with the application.

 

Insert command

 

This statement is used to insert a row of data in a table.

Dim ins As String = "insert into emp values(1,'monu')"

Dim com As New SqlCommand(Ins, con)

 

Now we create a database table and insert some values in this table. Table looks like this.

 

create table emp

(

empid varchar(40),

empname varchar(30) 

)

go

insert into employee values(1,'monu')

go

select * from emp

OUTPUT


ta1.gif

 

Table1.gif

 

For example

 

Imports System.Data.SqlClient

Module Module1

    Sub Main()

        Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

        Dim con As New SqlConnection(str)

        Try

            con.Open()

            Dim ins As String = "insert into emp values(2,'Hari')"

            Dim com As New SqlCommand(ins, con)

            com.ExecuteNonQuery()

            Console.WriteLine("record has been saved")

        Catch ex As Exception

            Console.WriteLine("can not save record")

        End Try

    End Sub

End Module

 

OUTPUT


ta2.gif 

Now open the database table and test it.

 

ta3.gif

Table2.gif

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor