SqlDataAdapterとInsertCommand VB.NET

      2017/07/13

InsertCommandについて書きます。

InsertCommandはデータテーブル等とAdapterに橋渡しします。

データテーブルに1行データを追加するとします。

その場合データローを使いデータテーブルに追加して見てみましょう。

更新の前にInsertCommandを使わないといけません。

ソース
Imports System.Data.SqlClient
Public Class Form1
Dim cn As New SqlConnection(
"Data Source=(local)\SQL;" +
"Initial Catalog=ADO;" +
"Integrated Security=True;Pooling=False")
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = New SqlCommand()
adapter.SelectCommand.CommandText = "select * from meibo where number = @number"
adapter.SelectCommand.Parameters.Add(New SqlParameter("@number", TextBox1.Text))
adapter.SelectCommand.Connection = cn

Dim table As New DataTable()
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = New SqlCommand()
adapter.SelectCommand.CommandText = "select * from meibo"
adapter.SelectCommand.Parameters.Add(New SqlParameter("@number", TextBox1.Text))
adapter.SelectCommand.Connection = cn

Dim table As New DataTable()
adapter.Fill(table)

Dim dr As DataRow = table.NewRow
dr("number") = CInt(TextBox1.Text)
dr("name") = TextBox2.Text
dr("部署コード") = TextBox3.Text
table.Rows.Add(dr)

adapter.InsertCommand = New SqlCommand()
adapter.InsertCommand.CommandText = "INSERT INTO meibo (Name, Number,部署コード)VALUES( @name,@number,@busyocode)"
adapter.InsertCommand.Connection = cn

Dim sqlpram As SqlParameter = New SqlParameter

sqlpram.ParameterName = "@name"
sqlpram.SourceColumn = "name"
adapter.InsertCommand.Parameters.Add(sqlpram)

Dim sqlpram2 As SqlParameter = New SqlParameter

sqlpram2.ParameterName = "@number"
sqlpram2.SourceColumn = "number"
adapter.InsertCommand.Parameters.Add(sqlpram2)

Dim sqlpram3 As SqlParameter = New SqlParameter

sqlpram3.ParameterName = "@busyocode"
sqlpram3.SourceColumn = "部署コード"
adapter.InsertCommand.Parameters.Add(sqlpram3)

adapter.Update(table)

End Sub
End Class

PR



 - ADO.NET

Translate »