Definitely not. At least not this way. You're using ADO.Net, right? Then mount the query with the existing component to do this build. In this case, SQLCommand
. You pass the parameters through it. Example:
using (var connection = new SqlConnection(connectionString)) {
var query = "SELECT nome, idade FROM Pessoas ";
if (nome != "") {
query += " WHERE nome LIKE '%@Nome%'";
}
query += " ORDER BY idade"; //deixei mas poderia otimizar isto
var command = new SqlCommand(query, connection);
command.Parameters.Add("@Nome", SqlDbType.NVarChar);
command.Parameters["@Nome"].Value = nome;
try {
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (SQLException ex) {
Console.WriteLine(ex.Message); //só exemplo, deveria fazer algo mais
}
}
Note that assembling the basic text of the fixed part is not a big problem. Of course, if you have too much concatenation it's best to use a StringBuilder
to avoid large copies of data from one string to another , already that this type is immutable and can be very large.
var query = new StringBuilder("SELECT nome, idade FROM Pessoas ");
if (nome != "") {
query.Append(" WHERE nome LIKE '%@Nome%'");
}
query.Append(" ORDER BY idade"); //deixei mas poderia otimizar isto
What you can not do is concatenate the variable part, because the SQL Injection can occur there. You need to leave the insertion of the part coming externally to a method that knows how to deal with this type of problem.
Note that you have to identify in the query what the parameter is and then send it, all by class SQLCommand
.
This may not solve all security issues, but it is already a breakthrough.