What is SQL Injection attack and how to prevent it?

SQL injection means injecting some SQLcommands in SQL statements to hack your data or delete data or change your data in tables via web page input.

enter text like “10 or 1=1

It returns all the rows from table because our textbox input value converts query

select Name,Total=value from countrydetails where value =10 or 1=1

In above query it will check for value =10 as well as it will check for 1=1 means always true that’s the reason it will returns all the values from table this way they can inject values to change our queries and access all the values from table.

In another case if user enters value like “10; Drop TABLE countrydetails” in it will drop table from our database because our query will changed like this

select Name,Total=value from countrydetails where value =10; Drop TABLE countrydetails

To avoid these SQL injection attacks always we need to use parameterized queries like as shown below

DataTable dt = new DataTable();

using (SqlConnection con = new SqlConnection(“Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB”))

{

con.Open();

SqlCommand cmd = new SqlCommand(“select Name,Total=value from countrydetails where value =@value”, con);

cmd.Parameters.AddWithValue(“@value”, txtSearch.Text);

SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(dt);

con.Close();

gvDetails.DataSource = dt;

gvDetails.DataBind();

}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s