Rolling Back a Transaction with MySQL Connector in VB.net

Posted by Jonathan on Stack Overflow See other posts from Stack Overflow or by Jonathan
Published on 2010-04-20T01:07:54Z Indexed on 2010/04/20 1:13 UTC
Read the original article Hit count: 356

Filed under:
|
|

Hey all-

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

Thanks-

Jonathan

© Stack Overflow or respective owner

Related posts about mysql

Related posts about rollback