C# sqlite injection [duplicate]

这一生的挚爱 提交于 2019-12-05 10:46:35

问题


If I change my select from

String insSQL2
    = "select * from Produtos where nome = '" + txtBuscaNome.Text + "'"

To

String insSQL2
    = "select * from Produtos where nome = ''" + txtBuscaNome.Text + "''"

Will it prevent sql injection?


回答1:


No.

SQL injection isn't about creatively using quote characters. It's about treating input as data instead of as code. Take a look at a classic SQL injection vulnerability:

"SELECT * FROM Users WHERE Id = " + someValue;

It may intuitively look like you're using someValue as a data value, but you're actually using it as actual SQL code. The SQL engine doesn't see this as a value parameter, it sees it as part of the command being executed. That code should just be a value, but it can be anything. And you'd be executing whatever code is supplied.

Thinking of it in this way, it becomes clear that you should never execute user-supplied code in your application.

The alternative is to treat the user input as values in pre-defined code. That way you control the complete scope of the code and users are only supplying values. Which would look more like this:

"SELECT * FROM Users WHERE Id = @id";

Now the SQL engine sees that parameter (@id) and expects you to supply a value for that parameter. In ADO.NET it might look something like:

someCommand.Parameters.AddWithValue("@id", someValue);

Now the SQL engine knows that this is a data value and not code, so it treats it as data instead of executing it.




回答2:


No, it won't prevent sql injection.

Use parameterized sql:

var insSQL2 = "select * from Produtos where nome = @nome";
var connection = new SqlConnection(/* connection info */);
var command = new SqlCommand(insSQL2, connection);
command.Parameters.AddWithValue("@nome", txtBuscaNome.Text);


来源:https://stackoverflow.com/questions/21225354/c-sharp-sqlite-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!