Good evening,
I’m using the following code to truncate a table in my MySQL database. From what I can tell, the query is running fine and the tables are being truncated. However, the if statement that I’m using to test if rows are affected is being evaluated on the Else statement.
So how come the table in the database is being truncated – as expected – but the Else statement is being evaluated – as if no rows are affected? What am I doing wrong?
HERE’S THE CODE:
Public Sub purgeCC()
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
Dim ConnectionString As String = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Dim myQuery As String = "TRUNCATE TABLE cc_master"
Using dbConn As New MySqlConnection(ConnectionString)
Using dbComm As New MySqlCommand()
With dbComm
.Connection = dbConn
.CommandType = CommandType.Text
.CommandText = myQuery
End With
Try
Dim affectedRow As Integer
dbConn.Open()
affectedRow = dbComm.ExecuteNonQuery()
If affectedRow > 0 Then
MsgBox("Credit Card Master table has been successfully purged!", MsgBoxStyle.Information, "DATABASE PURGED!")
Else
MsgBox("Credit Card Master table was not purged!", MsgBoxStyle.Critical, "ATTENTION")
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbConn.Close()
dbComm.Dispose()
End Using
End Using
End Sub
Per this document http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html
the truncate command may not always return the rows affected if the DB version is greater than 5.somthing and the table does not have foreign key constraints. if you do have FKs then a delete is processed for each row and you get the return value you are seeking, but if you don’t then mysql will drop and re-add the table (which is much faster), which means it has no ideas how many records were affected.