1

i have problem trying to delete record from my VS 2012 and i'm using sql server 2012, this is my task from my lecturer, and i cant solved it

now this is what i have

Private Sub bt_hapus_Click(sender As Object, e As EventArgs) Handles bt_hapus.Click
    Try
        Dim sqlda As New SqlClient.SqlDataAdapter("Delete from tabelpasien where No_Rkm_Mds=" & Me.txt_rkm_mds.Text, Me.SqlConnection1)
        sqlda.Fill(dspasien, "tabelpasien")
        MsgBox("Data telah berhasil dihapus")
        bersih()
        pasif()
        normal()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

any help would be greatly apreciated...

codingbiz
  • 25,638
  • 8
  • 55
  • 93
user2775540
  • 45
  • 1
  • 7
  • What is the datatype of the field `No_Rkm_Mds`? – Steve Sep 23 '13 at 14:28
  • Then, the error are the missing quotes around the textbox value, but, as I have explained in my answer below, NEVER use string concatenation to build an SQL command. – Steve Sep 23 '13 at 14:42

3 Answers3

6

A delete command is executed using an SqlCommand and the ExecuteNonQuery method.

Your code should be

Try
    Dim cmd = New SqlClient.SqlCommand("Delete from tabelpasien where No_Rkm_Mds=@rkm", Me.SqlConnection1)
    cmd.Parameters.AddWithValue("@rkm", Me.txt_rkm_mds.Text)
    cmd.ExecuteNonQuery()
    ....

Using a parameterized query you don't have to put quotes around your where values (if the underlying field is any kind of char/varchar/nvarchar type) but, the most important benefit of a parameterized query is the elimination of a possible Sql Injection attack

Community
  • 1
  • 1
Steve
  • 208,592
  • 21
  • 221
  • 278
1

You have forgotten your single quote marks I.E." ' " from around your condition.

Your statement Should be

Delete From tabelpasien where No_Rkm_Mds='" + Me.txt_rkm_mds.Text + "'"

GeoffWilson
  • 443
  • 7
  • 20
1

If this is SQL SERVER, there shouldn't be a FROM in the statement.

Dim sqlda As New SqlClient.SqlDataAdapter("DELETE tabelpasien where No_Rkm_Mds=" & Me.txt_rkm_mds.Text, Me.SqlConnection1)

If No_Rkm_Mds is a VARCHAR or NVARCHAR, etc..., the value must be wrapped in 's.

Dim sqlda As New SqlClient.SqlDataAdapter("DELETE tabelpasien where No_Rkm_Mds=`" & Me.txt_rkm_mds.Text & "`", Me.SqlConnection1)

Finally, you should consider using SQL Parameters to avoid SQL injection.

Khan
  • 17,118
  • 3
  • 45
  • 58