ADO.NET Insert command in VB.NET

Here we see how to use ADO.net to insert the data to a SQL Server database using insert command.
  • 9434
Download Files:
 

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

 

output-in-vb.net.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


command-prompt-in-vb.net.gif
 

Now open the database table and test it.

 

database-table-list-in-vb.net.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.