0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VB.NETでDB操作する

Last updated at Posted at 2024-06-15

前提条件

・DBは"MicroSoftSManagimentStudio"を使用
・BookListというテーブルから値を取得する
・データテーブルを使用する

ID Name Author ReadFlg
1 プラネタリウムのふたご いしいしんじ true
2 medium 相沢渉呼 false
3 ハーモニー 伊藤計劃 false

SELECT

・データセットでDB接続されている(dsDataSet.xsd)
 ・データセット名:dsDataSet
・取得した値をaspxに表示する(BookIDをViewStateに保持する)

BookList.vb
Dim DBConStr As String = "接続文字列"
Using ta As New dsBookListTableAdapters.BookListTableAdapter(DBConStr)
  ' データを取得
  Dim dt As New dsBookList.BookListDataTable()
  'ページデータセットに保持する場合
  'PageDataSet.M_BookList = New dsBookList.BookListDataTable()
  ta.Fill(dt)
  'ta.Fill(PageDataSet.M_BookList)
End Using


INSERT or UPDATE

トランザクションにする

BookList.vb
Using tran As New Transactions.TransactionScope(Transactions.TransactionScopeOption.Required)
  Using ta As New dsBookListTableAdapters.BookListTableAdapter(DBConStr)
    ' 特定のIDでデータを取得
    Dim dt As New dsBookList.BookListDataTable()
    ta.FillByID(dt, book.ID)

    If dt.Rows.Count = 0 Then
      ' 取得できなかった場合は新規登録
      Dim newRow As DataRow = dt.NewRow()
      With newRow
        ' IDはIdentityとして設定しない
        .Item("Name") = book.Name
        .Item("Author") = book.Author
        .Item("ReadFlg") = book.ReadFlg
      End With
      dt.Rows.Add(newRow)
    Else
      ' 取得できた場合は更新
      Dim row As dsBookList.BookListRow = dt.Rows(0)
      row.Name = book.Name
      row.Author = book.Author
      row.ReadFlg = book.ReadFlg
    End If

    ta.Update(dt)
  END Using
  tran.Complete()
END Using

'PageDataSetに既にta.FillByID(dt, book.ID)で取得したデータがあり、それをベースとする場合
Using tran As New Transactions.TransactionScope(Transactions.TransactionScopeOption.Required)
  Using ta As New dsBookListTableAdapters.BookListTableAdapter(DBConStr)
    ' 特定のIDでデータを取得
    Dim dt As dsBookList.BookListDataTable = PageDataSet.M_BookList

    If dt.Rows.Count = 0 Then
      ' 取得できなかった場合は新規登録
      Dim newRow As dsBookList.BookListRow = dt.NewBookListRow()
      With newRow
        ' IDはIdentityとして設定しない
        .Item("Name") = book.Name
        .Item("Author") = book.Author
        .Item("ReadFlg") = book.ReadFlg
      End With
      dt.AddBookListRow(newRow)
    Else
      ' 取得できた場合は更新
      Dim row As dsBookList.BookListRow = CType(dt.Rows(0), dsBookList.BookListRow)
      row.Name = book.Name
      row.Author = book.Author
      row.ReadFlg = book.ReadFlg
    End If

    ta.Update(dt)
  END Using
  tran.Complete()
END Using
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?