Search code examples
sqlvb.netsql-delete

VB SQL DELETE Statement Not Working - No Error At All


This is my Code and it just doesn't work, I'm trying to make it Delete a record where the column staffID is equal to the variable currentStaffID although it doesn't delete the record or give an error, it just carries on and displays the MsgBox after the DELETE Statement.

Dim AreYouSureEdit = MsgBox("Are you sure you want to delete this record?", MsgBoxStyle.YesNo)

    If DbConnect() And AreYouSureEdit = MsgBoxResult.Yes Then

        Dim SQLCmd As New OleDbCommand
        SQLCmd.Connection = cn
        currentStaffID = editStaffIDTxtBox.Text()

        SQLCmd.CommandText = "DELETE * STAFF WHERE staffID = @currentStaffID"
        cn.Close()

        MsgBox("Record Deleted.", MsgBoxStyle.OkOnly)

    End If

Solution

  • You're setting up your command and everything - but you're never executing it! Of course nothing happens.....

    You need to add one line of code:

    Dim SQLCmd As New OleDbCommand
    SQLCmd.Connection = cn
    currentStaffID = editStaffIDTxtBox.Text()
    
    SQLCmd.CommandText = "DELETE * STAFF WHERE staffID = ?"
    
    '' You need to define the parameter and set its value here!
    SQLCmd.Parameters.Add("p1", OleDbType.Int).Value = currentStaffID;
    
    '' you need to actually **EXECUTE** your DELETE query!
    SQLCmd.ExecuteNonQuery()
    
    cn.Close()
    

    Also, while you're setting up a parameter in your SQL query text just fine, I don't see where you're actually defining such a parameter on your SQLCmd object - and also be aware: OleDB doesn't use named parameters (like the native SQL Server client does) - it uses positional parameters (so that's what I replaced your named parameter with just a ?). Since there's only one parameter, this shouldn't be a problem here - but you need to properly define the SQLCmd's parameter (and set its value)