LoginSignup
1
1

More than 5 years have passed since last update.

インスタンスでDataAdapter,DataTableを保持せずにDataAdapterでデータベースの値を更新する

Last updated at Posted at 2015-08-05

そういう要求があって調べる機会があったので、こういうこともできるという備忘録的に

Form1.vb
Imports System.Data.SqlClient
Imports System.Text

Public Class Form1
    Private connectionString As String = "適当な接続文字列"

    'dataGridViewにデータ格納
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim sql As New StringBuilder

        sql.AppendLine("SELECT")
        sql.AppendLine("    P_Key,")
        sql.AppendLine("    value1,")
        sql.AppendLine("    value2")
        sql.AppendLine("FROM")
        sql.AppendLine("    Test")

        Dim con As New SqlConnection(connectionString)
        Dim cmd As New SqlCommand(sql.ToString, con)
        Dim da As New SqlDataAdapter(cmd)

        Dim dt As New DataTable

        con.Open()

        da.Fill(dt)

        DataGridView1.DataSource = dt

        con.Close()

    End Sub

    'dataGridViewの変更をSQLServerに反映
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Dim sql As New StringBuilder

        sql.AppendLine("SELECT")
        sql.AppendLine("    P_Key,")
        sql.AppendLine("    value1,")
        sql.AppendLine("    value2")
        sql.AppendLine("FROM")
        sql.AppendLine("    Test")

        Dim con As New SqlConnection(connectionString)
        Dim cmd As New SqlCommand(Sql.ToString, con)
        Dim da As New SqlDataAdapter(cmd)

        Dim dt As DataTable = New DataTable

        con.Open()

        da.Fill(dt)

        dt.Merge(CType(DataGridView1.DataSource, DataTable))

        da.Update(dt)

        con.Close()

    End Sub

End Class

まぁ普通は素直にインスタンスでDataAdapterとConnection保持しろって話になるんですが。
データベースへの接続用のクラスがSELECT終わる度にConnectionをDisposeするような実装になってたりする場合は選択肢に入るかもしれない。

そもそもDataAdapterによる更新を使う機会が多くないってのは無し

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1