SqlDataAdapterとDeleteCommand VB.NET

      2017/07/13


今回はDeleteCommandです。
正直あまり必要性を感じないです。

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 "

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

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.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)

adapter.DeleteCommand = New SqlCommand()
adapter.DeleteCommand.CommandText = "DELETE meibo where number = @number"
adapter.DeleteCommand.Parameters.Add(New SqlParameter("@number", TextBox1.Text))
adapter.DeleteCommand.Connection = cn
cn.Open()
adapter.DeleteCommand.ExecuteNonQuery()
cn.Close()

End Sub

End Class

adapter.DeleteCommand.ExecuteNonQueryで実行してます。
adapterのコマンドにExecuteNonQueryオプションあったんですね。
コネクションを繋いでるのでコマンド経由と一緒ですがw
このソースadapter使う意味ないですね。

PR



 - ADO.NET

Translate »