Click here to Skip to main content
15,940,246 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to protect below query of sql from sql injection attack please suggest i have studied the sql injection but i didnt get
sql="Select * from adminuserdata where username='" & username & "'"
Posted
Comments
walterhevedeich 25-Jul-11 1:32am    
What language are you using? C#? VB? PHP? You might want to mention it as well.

1 solution

Without knowing the language you are using, it is very difficult to be more than general.
However, there are two ways to protect yourself from SQL Injection attacks:
1) Encoding characters in strings, and decoding them later.
2) Paramaterized queries.

The first works by replacing characters which can have significance to SQL before the data is presented:
';', '&', '[', ']', quote and double quote is s sensible starting list. So a string like "hello&there';--" might be presented to the database as "hello&there&qt;≻--" - the string must then be decoded before use.

The second works by providing placeholders in the SQL statement which are replaced with parameters when it executes that. Since the data is never passed through the statement processor, it can never be interpreted as a command. In C#:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn1, myColumn2) VALUES (@C1, @C2)", con))
        {
        com.Parameters.AddWithValue("@C1", myValueForColumn1);
        com.Parameters.AddWithValue("@C2", myValueForColumn2);
        com.ExecuteNonQuery();
        }
    }


The later is (generally) easier to use, and a lot clearer to read. It also requires no processing on data retrieval, and doesn't interfere with any encoding used to prevent HTML based attacks!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900