Export Datatable ke SQL Server VB.NET

Pada postingan kali ini saya akan share cara mengeksport data dari datatable ke tabel pada SQL server, misalnya saya contohkan disini kita mempunyai database dengan nama ‘dbTes’ kemudian terdapat satu tabel dengan nama T_User dengan struktur:

UserAccount varchar(20)
Password varchar(20)

Oke langsung saja, berikut coding untuk exportnya menggunakan VB.NET


Datatable To SQL

Imports System.Data.SqlClient

Public Class FrmDatatable
    Dim dt As DataTable

    Private Sub BtnCreateDT_Click(sender As System.Object, e As System.EventArgs) Handles BtnCreateDT.Click
        dt = New DataTable
        dt.Columns.Add("UserAccount")
        dt.Columns.Add("Password")

        Dim row As DataRow = dt.NewRow
        row("UserAccount") = "Admin"
        row("Password") = "Admin"

        dt.Rows.Add(row)

        row = dt.NewRow
        row("UserAccount") = "Didi"
        row("Password") = "123"

        dt.Rows.Add(row)

        Grid.DataSource = dt
    End Sub

    Private Sub BtnExport_Click(sender As System.Object, e As System.EventArgs) Handles BtnExport.Click
        Dim cn As New SqlConnection("Server=(local);Database=dbTes;User ID=sa;Password=admin212;Trusted_Connection=False;")
        cn.Open()
        Dim bulkcopy As New SqlBulkCopy(cn)

        bulkcopy.DestinationTableName = "dbo.T_User"
        bulkcopy.WriteToServer(dt)

        bulkcopy.Close()
        bulkcopy = Nothing
        dt.Dispose()
        cn.Close()
        cn.Dispose()
    End Sub
End Class

Selamat mencoba, semoga bermanfaat..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: