How to fix syntax error: 'Incorrect syntax near the keyword 'WHERE'.'

57 Views Asked by At
cmdUpdate.CommandText = "UPDATE Products2 " +
                " SET ProductName = '" + txtProductName.Text + "', " +
                " Description = '" + txtDescription.Text + "' , " +
                " Quantity = '" + txtQuantity.Text + "' , " +
                " CriticalLevel = '" + txtCriticalLevel.Text + "' , " +
                " PurchasePrice = '" + txtPurchasePrice.Text + "' , " +
                " SellingPrice = '" + txtSellingPrice.Text + "' , " +
                " ProductStatus = '" + cboStatus.Text + "' , " +
                " Created = '" + dtpCreated.Value.Date.ToString() + "' , " +
                " LastModified = '" + dtpLastModified.Value.Date.ToString() + "' , " +
                "WHERE (ProductNo=" + txtProdNo.Text + ");";

How do I fix this code?

System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'WHERE'.'

1

There are 1 best solutions below

0
Zohar Peled On

The smallest problem you have is that last comma before the WHERE.
The larger one is the huge security hazard caused by concatenating user input into your SQL statement.
Instead, use parameters. That will also make your code much more readable:

cmdUpdate.CommandText = "UPDATE Products2 " +
                " SET ProductName = @ProductName, " +
                " Description = @Description, " +
                " Quantity = @Quantity, " +
                " CriticalLevel = @CriticalLevel, " +
                " PurchasePrice = @PurchasePrice, " +
                " SellingPrice = @SellingPrice, " +
                " ProductStatus = @ProductStatus, " +
                " Created = @Created, " +
                " LastModified = @LastModified" +
                " WHERE ProductNo = @ProductNo);";

// Note: I'm assuming SqlServer and also the type and size of the columns.
// Change it to match your actual needs.
cmdUpdate.Parameters.Add(@ProductName, SqlDbType.NVarChar, 30).Value = txtProductName.Text;
cmdUpdate.Parameters.Add(@Description, SqlDbType.NVarChar, 255).Value = txtProductName.Text;

// and add all other parameters as well

Why is SQL injection still a thing?