前提条件
・DBは"MicroSoftSManagimentStudio"を使用
・BookListというテーブルから値を取得する
・データアダプタを使用
(identity) | (nvarchar(50)) | (nvarchar(50)) | (varchar(19)) |
---|---|---|---|
BookID | BookName | Author | ReadingCompletionDate |
1 | プラネタリウムのふたご | いしいしんじ | 2024/02/01 |
2 | medium | 相沢渉呼 | 2024/02/10 |
3 | ハーモニー | 伊藤計劃 | 2024/03/10 |
SELECT
・データセットでDB接続されている(dsDataSet.xsd)
・データセット名:dsDataSet
・取得した値をaspxに表示する(BookIDをViewStateに保持する)
BookList.vb
Dim DBConStr As String = "接続文字列"
Using ta As New dsDataSetTableAdapters.BookListTableAdapter(DBConStr)
Dim dt As New dsDataSet.BookListDataTable
ta.Fill(dt)
If dt.Count <> 0 Then
With dt(0)
.BookID = ViewState(BOOK_ID)
.BookName = lblBookName.Text
.Author = lblAuthor.Text
End With
End If
End Using
INSERT
トランザクションにする
BookList.vb
Using tran As New Transactions.TransactionScope(Transactions.TransactionScopeOption.Required)
Using ta As New dsDataSetTableAdapters.BookListTableAdapter(DBConStr)
Using dt As dsDataSet.BookListDataTable
Dim dr = dt.NewBookListRow
With dr
.BookName = txtBookName.Text
.Author = txtAutor.Text
.ReadingCompletionDate = CStr(DateTime.Now)
End With
dt.AddBookListRow(dr)
If ta.Update(dt) = 1 Then
'登録成功時の処理
Else
'登録失敗時の処理
End If
END Using
END Using
tran.Complete()
END Using
UPDATE
BookList.vb
Using tran As New Transactions.TransactionScope(Transactions.TransactionScopeOption.Required)
Using ta As New dsDataSetTableAdapters.BookListTableAdapter(DBConStr)
Using dt As dsDataSet.BookListDataTable
End If
With dt(0)
.BookName = txtBookName.Text
.Author = txtAutor.Text
End With
If ta.Update(dt) = 1 Then
'更新成功時の処理
Else
'更新失敗時の処理
End If
END Using
END Using
tran.Complete()
END Using
既存の場合はUPDATE、新規の場合はINSERT
FillやGetDataで取得し、結果によって分岐させる
BookList.vb
Using tran As New Transactions.TransactionScope(Transactions.TransactionScopeOption.Required)
Using ta As New dsDataSetTableAdapters.BookListTableAdapter(DBConStr)
Using dt As dsDataSet.BookListDataTable
da.Fill(dt,bookID)
'更新
If dt.Count > 0 Then
With dt(0)
.BookName = txtBookName.Text
.Author = txtAutor.Text
End With
Else
'新規
Dim dr = dt.NewBookListRow
With dr
.BookName = txtBookName.Text
.Author = txtAutor.Text
.ReadingCompletionDate = CStr(DateTime.Now)
End With
dt.AddBookListRow(dr)
End If
If ta.Update(dt) = 1 Then
'更新成功時の処理
Else
'更新失敗時の処理
End If
END Using
END Using
tran.Complete()
END Using