Definitely not. At least not this way. You’re using ADO.NET, right? Then assemble the query with the existing component to make this construction. In the case is the 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 mounting the basic text of the fixed part is not a big problem. Of course if you have too much concatenation it is better to use a StringBuilder
for avoid large copies of data from a string to another, since this guy 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
I put in the Github for future reference.
What you can’t do is concatenate the variable part, because then the SQL Injection. Need to leave the insertion of the part that comes externally to a method that knows how to deal with this type of problem.
Note that you have to identify in the query what is the parameter and then send it, all by class SQLCommand
.
This may not solve all the security problems, but it’s a breakthrough.
I have some querys with many lines, I’m already using the
Parameters
I’ll use theStringBuilder
to concatenate.– gato