Rolling Back a Transaction with MySQL Connector in VB.net
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.
精彩评论