开发者

Rolling Back a Transaction with MySQL Connector in VB.net

开发者 https://www.devze.com 2022-12-27 23:45 出处:网络
I have one multi-row INSERT statement (300 or so sets of values) that I would like to commit to the MySQL database in an all-or-nothing fashion.

I have one multi-row INSERT statement (300 or so sets of values) that I would like to commit to the MySQL database in an all-or-nothing fashion.

insert into table VALUES
(1, 2, 3),
(4, 5, 6),
(7, 8, 9);

In some cases, a set of values in the command will not meet the criteria of the table (duplicate key, for example). When that happens I do not want any of the previous sets added to the database. I've implemented this with the following code, however, my rollback command doesn't appear to be making a difference. I've used this documentation: http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqltransaction.html

Dim transaction As MySqlTransaction = sqlConnection.BeginTransaction()
sqlCommand = New MySqlCommand(insertStr, sqlConnection, transaction)
Try
    sqlCommand.ExecuteNonQuery()
Catch ex As开发者_C百科 Exception
    writeToLog("EXCEPTION: " & ex.Message & vbNewLine)
    writeToLog("Could not execute " & sqlCmd & vbNewLine)
    Try
        transaction.Rollback()
        writeToLog("All statements were rolled back." & vbNewLine)
        Return False
    Catch rollbackEx As Exception
        writeToLog("EXCEPTION: " & rollbackEx.Message & vbNewLine)
        writeToLog("All statements were not rolled back." & vbNewLine)
        Return False
    End Try
End Try
transaction.commit()

I get the DUPLICATE KEY exception thrown, no Rollback Exception thrown, and every set of values up to duplicate key committed to the database. What am I doing wrong?


Are you using MyISAM tables (the default) ? MyISAM does not support transactions. Use InnoDB tables if you need transactions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号