Reputation: 438
Hi I am getting id value from a drop down list and passing it to a code behind method which passes value to sql to do some operation.
I was wondering if it is the right way of doing it.
if it is not then why not and how someone can inject it with sql injection and what would be the solution.
protected void Drop1_SelectedIndexChanged(object sender, EventArgs e)
{
int abcID;
abcID= Convert.ToInt32(drop1.SelectedItem.Value);
string sc = "SELECT dddd FROM table1 WHERE abcID NOT IN("
+ abcID + ")";
using (SqlDataSource ds = new SqlDataSource(ConnectionString(), sc ))
{
}
Upvotes: 1
Views: 368
Reputation: 9074
You should use parametrized queries as follows:
string sc = "SELECT dddd FROM table1 WHERE abcID NOT IN(@par)";
cmd=new SqlCommand(sc,conn);
cmd.Parameters.AddWithValue("@par",abcID );
da=newsqldataadapter(cmd);
ds=new DataSet();
da.Fill(ds);
cmd.excutenonquery();
Go through Following:
http://en.wikipedia.org/wiki/SQL_injection
Upvotes: 3
Reputation: 508
Not a nice way to do things, but it would survive sql injection... so, no... u won't have that problem
Upvotes: 1
Reputation: 17724
Since you are using, Convert.ToInt32
on the value sent by the user, SQL injection would not occur. Invalid values would throw exceptions.
However it is a generally a good practice to use Parametrized queries.
That way even string values would be safe.
SqlCommand command = new SqlCommand("SELECT dddd FROM table1 WHERE abcID NOT IN(@myID)");
command.Parameters.AddWithValue("@myID", abcID);
Upvotes: 3
Reputation: 13568
Since you converted the value to a 32bit integer, you won't be having "injection" problems. There are better ways to escape values though. (see parameterization)
Upvotes: 1
Reputation: 70776
For best practice you should use parameterized queries instead.
SqlCommand command = new SqlCommand("SELECT dddd FROM table1 WHERE abcID NOT IN( @Value )"
command.Parameters.Add(new SqlParameter("Value", abcId));
You could assume that you are safe due to the fact that Convert.ToInt32
will throw a FormatException
if someone was to attempt to inject something like DROP TABLE table1;
into your drop down list and pass it back to the server. However, I would strongly recommend the use of paramertized queries.
Upvotes: 1
Reputation: 33563
No, this particular example cannot be used for SQL injection.
However, if you train yourself to always use stored procedures or parametrized queries, you will never get it into your system to create SQL statements like this. This way, you will never make something (possible by accident) that would create SQL injection attack vectors.
Upvotes: 1