Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.format(): multiline string without using plus

Tags:

c#

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%';"; 
like image 673
Mike Avatar asked Mar 23 '26 04:03

Mike


2 Answers

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.

like image 93
Daniel Brückner Avatar answered Mar 26 '26 11:03

Daniel Brückner


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%"));
like image 37
AxelEckenberger Avatar answered Mar 26 '26 12:03

AxelEckenberger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!