System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.' / cmd.ExecuteNonQuery()

43 Views Asked by At
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If NamaBukuBox.Text = " " Or PngrngBukuBox.Text = " " Or PnrbtBukuBox.Text = " " Or JmlhBukuBox.Text = " " Then
        MsgBox("Isi Semua Kolom Informasi")
    Else
        Con.Open()
        Dim query = "Insert into BukuTbl values('" & NamaBukuBox.Text & "','" & PngrngBukuBox.Text & "','" & PnrbtBukuBox.Text & "'," & JmlhBukuBox.Text & ")"
        Dim cmd As SqlCommand
        cmd = New SqlCommand(query, Con)
        cmd.ExecuteNonQuery() '** this line is error
        MsgBox("Buku Telah Ditambahkan")
        Con.Close()
    End If
End Sub

I don't know what to do what makes the error and how to solve it?

1

There are 1 best solutions below

2
On

This is a very risky way of writing code. User input would be inserted directly into SQL. If your user inputs any apostrophe, your SQL will fail.

For example, try entering Abc's into the NamaBukuBox text box. Check your resulting SQL. In the worst case scenario, a user could inject SQL and delete data and tables.

In your case, it is likely the input from the user that is causing the SQL to fail. Please use parameters to input user data into SQL. Do not concatenate user input direct in SQL. You SQL should look something like:

Insert into BukuTbl values(@NamaBukuBox,@PngrngBukuBox,@PnrbtBukuBox,@JmlhBukuBox)