1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Visual Basic Transactionサンプル

Posted at

トランザクション

データの追加や更新を行う際に

すべての処理が正しく行われた場合のみ変更を反映させたく、どこかで失敗した場合は

すべての処理が行われないようにするためのもの

サンプル

Imports System.Data.SqlClient

Public Class Form1

    Private cn As SqlConnection = New SqlConnection()
    Private cmd As SqlCommand = New SqlCommand()
    Private cn_str = "接続文字列を設定"

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        cn.ConnectionString = cn_str
        cn.Open()
        cmd.Connection = cn
        cmd = cn.CreateCommand()
        cmd.CommandType = CommandType.Text

        Dim sqlTransaction As SqlTransaction

        ' トランザクションを開始
        sqlTransaction = cn.BeginTransaction
        cmd.Transaction = sqlTransaction



        Try
            ' 複数のコマンド実行
            cmd.CommandText = "INSERT INTO USERS (Id,Name,Age) VALUES (4, 'name', 12)"
            cmd.ExecuteNonQuery()

            cmd.CommandText = "INSERT INTO USERS (Id,Name,Age) VALUES (, 'second user', 24)"
            cmd.ExecuteNonQuery()

            sqlTransaction.Commit()

        Catch ex As Exception
            sqlTransaction.Rollback()
            MessageBox.Show(ex.Message)

        End Try

        cmd.Dispose()
        cn.Close()
    End Sub

End Class

上記のサンプルの

sqlTransaction = cn.BeginTransaction

の部分からトランザクションが始まり

sqlTransaction.Commit()

にて処理を行い

もし何かしらの例外が発生した場合は


sqlTransaction.Rollback()

によって処理をすべてロールバックしています。

終わり。

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?