LoginSignup
0
0

More than 1 year has passed since last update.

ループが絡むトランザクション

Posted at
sample_transaction.vb
Try

    ' SQLServerに接続する
    Dim con As New SqlConnection(
    "Data Source=hoge\SQLEXPRESS;" +
    "Initial Catalog=hoge;" +
    "Integrated Security=True")
    Dim cmd As New SqlCommand
    Dim sql As New StringBuilder
    con.Open()
    cmd.Connection = con

    'トランザクション
    Dim tran As SqlTransaction
    tran = con.BeginTransaction

    Try

        sql.AppendLine("INSERT INTO dbo.EMPLOYEES ")
        sql.AppendLine("( ")
        sql.AppendLine("  id, name ")
        sql.AppendLine(") VALUES ( ")
        sql.AppendLine("  @id, @name ")
        sql.AppendLine("); ")

        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql.ToString()

        For i As Integer = 0 To dt.Rows.Count - 1

            cmd.Parameters.Clear()
            cmd.Parameters.Add("@id", SqlDbType.Int).Value = dt.Rows(i).Item(0)
            cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = dt.Rows(i).Item(1)

            'プロシージャの実行
            cmd.Transaction = tran
            cmd.ExecuteNonQuery()

        Next i

        'コミット
        tran.Commit()

    Catch ex As Exception

        'ロールバック
        tran.Rollback()

    End Try

Catch ex As Exception
    MsgBox(ex.ToString)
End Try

0
0
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
0