φ(..) ビボ~6 φ(..)

主にAccess、VBAに関する備忘録

DataAdapter(DataTable)でレコードの更新をするサンプル

        Using cn As New SqlConnection(mConnectionString)
            cn.Open()

            Using cmd As New SqlCommand
                cmd.Connection = cn

                Dim SQL As New StringBuilder

                'INDEX列を含むコマンド文字列でないとダメかも...
                SQL.Append("SELECT * FROM TABLE_A")
                SQL.Append(" WHERE FLG_2 = @PARA1")
                SQL.Append(" ORDER BY FLD_1")

                cmd.CommandText = SQL.ToString

                cmd.Parameters.AddWithValue("@PARA1", 1)
                
                Using ad As New SqlDataAdapter(cmd)

                    '****↓必要↓****
                    ad.MissingSchemaAction = MissingSchemaAction.AddWithKey
                    
                    Dim bd As New SqlCommandBuilder(ad)
                    '****↑必要↑****

                    Dim tb As New DataTable

                    Try
                        ad.Fill(tb)

                        For i As Integer = 0 To tb.Rows.Count - 1
                            tb.Rows(i)("FLD_3") = "値"
                        Next i

                        ad.Update(tb)

                    Catch ex As Exception
                        MessageBox.Show(ex.Message, "エラー")
                    End Try

                End Using

            End Using
        End Using

MissingSchemaAction 列挙体 (System.Data)