Change
Change

Reputation: 438

Can this be victim of sql injection

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

Answers (6)

Freelancer
Freelancer

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

Davide
Davide

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

nunespascal
nunespascal

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

Gung Foo
Gung Foo

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

Darren
Darren

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

Bart Friederichs
Bart Friederichs

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

Related Questions