Is it safe to not parameterize an SQL query when the parameter is not a string?

前端 未结 11 835
一生所求
一生所求 2020-12-23 15:57

In terms of SQL injection, I completely understand the necessity to parameterize a string parameter; that\'s one of the oldest tricks in the book. But when can

11条回答
  •  旧巷少年郎
    2020-12-23 16:23

    "SELECT * FROM Table1 WHERE Id=" + intVariable.ToString()
    

    Security

    It is OK.
    Attackers can not inject anything in your typed int variable.

    Performance

    Not OK.

    It's better to use parameters, so the query will be compiled once and cached for next usage. Next time even with different parameter values, query is cached and doesn't need to compile in database server.

    Coding Style

    Poor practice.

    • Parameters are more readable
    • Maybe it makes you get used to queries without parameters, then maybe you made a mistake once and use a string value this way and then you probably should say goodbye to your data. Bad habit!

    "SELECT * FROM Product WHERE Id=" + TextBox1.Text
    

    Although it is not your question, but maybe useful for future readers:

    Security

    Disaster!

    Even when the Id field is an integer, your query may be subject to SQL Injection. Suppose you have a query in your application "SELECT * FROM Table1 WHERE Id=" + TextBox1.Text. An attacker can insert into text box 1; DELETE Table1 and the query will be:

    SELECT * FROM Table1 WHERE Id=1; DELETE Table1
    

    If you don't want to use a parametrized query here, you should use typed values:

    string.Format("SELECT * FROM Table1 WHERE Id={0}", int.Parse(TextBox1.Text))
    

    Your Question

    My question arose because a coworker wrote a bunch of queries concatenating integer values, and I was wondering whether it was a waste of my time to go through and fix all of them.

    I think changing those codes is not waste of time. Indeed change is recommended!

    If your coworker uses int variables it has no security risk, but I think changing those codes is not waste of time and indeed changing those codes is recommended. It makes code more readable, more maintainable, and makes execution faster.

提交回复
热议问题