1

I'm very early on in learning SQL, but I've encountered the topic of SQL injections, and understand that parameters are probably the best way to prevent them. But I couldn't find any explanation of what they actually ARE.

So, for instance, in this code in ASP.NET (from w3schools):

txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();

What dos the "command.parameters.addwithvalue" actually do?

I'm sorry if this is a stupid question, but I couldn't find the answer to it - everywhere I look they just say "use parameters" but don't explain what that actually means...

Thanks!

iod
  • 7,412
  • 2
  • 17
  • 36
  • Well... `AddWithValue` is a method in the Ado.Net library. You might want to do some research on that method. It then leads on to other things like the parameters collection. I also suggest you run your code and inspect program variables during runtime and see if you can make sense of that. – Nick.Mc Oct 27 '14 at 04:43

1 Answers1

0

actually you need to make prepared statement to stop sql injection , another thing is you need to escape the query or add slashed before single quotes in order to qvoid SQL Injection

Form w3schools

"Some web developers use a "blacklist" of words or characters to search for in SQL input, to prevent SQL injection attacks.

This is not a very good idea. Many of these words (like delete or drop) and characters (like semicolons and quotation marks), are used in common language, and should be allowed in many types of input.

(In fact it should be perfectly legal to input an SQL statement in a database field.)

The only proven way to protect a web site from SQL injection attacks, is to use SQL parameters.

SQL parameters are values that are added to an SQL query at execution time, in a controlled manner.

ASP.NET Razor Example

txtUserId = getRequestString("UserId"); txtSQL = "SELECT * FROM Users WHERE UserId = @0"; db.Execute(txtSQL,txtUserId);

Note that parameters are represented in the SQL statement by a @ marker.

The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be executed. Another Example txtNam = getRequestString("CustomerName"); txtAdd = getRequestString("Address"); txtCit = getRequestString("City"); txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)"; db.Execute(txtSQL,txtNam,txtAdd,txtCit);"

A.B
  • 20,110
  • 3
  • 37
  • 71