I typically write my SQL as so in .NET
sql.Append("SELECT id, code, email FROM mytable WHERE variable = @variable ");
Then do something like this:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["defaultConnection"]].ConnectionString))
{
using (SqlCommand myCommand = new SqlCommand(sql.ToString(), conn))
{
myCommand.Parameters.AddWithValue("@variable", myVariableName");
...
But should I also do this addParameter when the data I got comes directly from the database like so?
likesql.Append(string.Format("SELECT group_id, like_text FROM likeTerms ORDER BY group_id ASC "));
DataTable dtLike = SqlHelper.GetDataTable(likesql.ToString());
foreach (DataRow dr in dtLike)
{
buildsql.Append(".... varId = " + dr["group_id"].ToString() + "...");
...
Is this acceptable? What is best practice?
In fact, you don't even need to be using ASP.NET to be susceptible to SQL injection attacks. Any application that queries a database using user-entered data, including Windows Forms applications is a potential target of an injection attack. Protecting yourself against SQL injection attacks is not very difficult.
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
SQL injection is a code injection technique that might destroy your database. SQL injection is one of the most common web hacking techniques. SQL injection is the placement of malicious code in SQL statements, via web page input.
SQL injection attacks can be performed in Entity SQL by supplying malicious input to values that are used in a query predicate and in parameter names. To avoid the risk of SQL injection, you should never combine user input with Entity SQL command text.
Can someone with limited database access inject directly into a field used elsewhere?
Also, it helps performance. Cached execution plans will disregard the value of the parameter, meaning you're saving the server from recompiling the query every time the parameters change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With