ADO.NET CommandBuilder Object in VB.NET

This article defines that we can insert value in database with out insert command using commandbuilder.
  • 3026
 

CommandBuilder

CommandBuilder generates insert, update, delete commands for Data adapter based on select command. Similar to other objects, each data provider has a command builder class. The OleDbCommandBuilder, SqlCommonBuilder, and OdbcCommandBuilder classes represent the CommonBuilder object in the OleDb, Sql, and ODBC data providers.

Creating a CommandBuilder Object

To create a Sqlcommandbuilder we must pass a DataAdapter as an parameter of the commandbuild.

Dim builder As New SqlCommandBuilder(adapter)

Now creating a table in Database and insert the value. like this

create table emp1

(

firstname varchar(20),

lastname varchar(30)

)

go

Insert into emp1 values('Rohatash','kumar')

Insert into emp1 values('Manoj','singh')

go

select * from emp1

OUTPUT

t1.gif 

Table1.gif

For example

The below example will insert the employee firstname and last name in the table emp1 from MS SQL server database.

Imports System.Data.SqlClient

Module Module1

    Sub Main()

        Dim con As New SqlConnection("Data Source=.;uid=sa; pwd=123;database=master")

        con.Open()

        Dim adapter As New SqlDataAdapter("SELECT * FROM Emp1 ORDER by firstname", con)

        Dim builder As New SqlCommandBuilder(adapter)

        Dim ds As New DataSet("EmployeeSet")

        adapter.Fill(ds, "Emp1")

        Dim EmployeeTable As DataTable = ds.Tables("Emp1")

        Dim row As DataRow = EmployeeTable.NewRow()

        row("FirstName") = "Bharat"

        row("LastName") = "kumar"

        EmployeeTable.Rows.Add(row)

        adapter.Update(ds, "Emp1")

        Console.WriteLine((row("FirstName").ToString().Trim() & " ") + row("LastName").ToString().Trim() & " Added to Emp1")

    End Sub

End Module

OUTPUT

t2.gif 

Now test the table firstname and last name has inserted.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.