how string.format() can help to avoid using "+" in such statement:
string statement =" SELECT DISTINCT titel as linieName" +
" FROM qry_Forecast_Taktzeiten" +
" WHERE linieName LIKE 'lin%';";
There is no need to avoid the plus operators here - the compiler joins string constants at compile time, hence the concatenation will not occur at runtime.
The statement above the + is used to concatenate seveal strings you created to make your code more readable. String.Format will not help you here!
To avoid the string concatenation you could do the following:
StringBuilder sb = new StringBuilder();
sb.Append(" SELECT DISTINCT titel as linieName");
sb.Append(" FROM qry_Forecast_Taktzeiten");
sb.Append(" WHERE linieName LIKE 'lin%';");
statement = sb.ToString();
If you want to replace the 'lin' with some variable you have you can use:
string statement =" SELECT DISTINCT titel as linieName" +
" FROM qry_Forecast_Taktzeiten" +
" WHERE linieName LIKE '{0}';";
statement = string.Format(staement, "lin%");
or
sb.AppendFormat(" WHERE linieName LIKE '{0}';", "lin%");
However, all of the methods above using string replacement ({0}) bear the risk of an SQL injection attack if the "lin%" is obtained from a user entry.
So the best bet is to use:
string statement =" SELECT DISTINCT titel as linieName" +
" FROM qry_Forecast_Taktzeiten" +
" WHERE linieName LIKE @match;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = statement;
cmd.Parameters.Add(new SqlParameter("@match", "lin%"));
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