Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid string concatenation to create queries

Tags:

sql

Martin Fowler in his book Patterns of enterprise application architecture says

A good rule of thumb is to avoid string concatenation to put together SQL queries

It is a practice that I use quite often, to abstract the syntax of my SQL queries from the real data of the query.

Can you explain me why this is considered a bad practice?

like image 771
marcosh Avatar asked Feb 12 '15 09:02

marcosh


People also ask

How do I stop concatenation in SQL?

A more secure approach is to create a collection of parameters in the SQL statement using string concatenation, and then supply the parameter values using a loop. This ensures that the user supplied values (or potentially user supplied values) are always provided to the database server as parameters.

Is string concatenation bad?

Due to this, mixing the StringBuilder and + method of concatenation is considered bad practice. Additionally, String concatenation using the + operator within a loop should be avoided. Since the String object is immutable, each call for concatenation will result in a new String object being created.

What can I use instead of concat in SQL?

Re: Alternatives to using Concat for SQL queriesTextJoin() is used to combine contents from different cells. You can specify a delimiter and you can ignore empty cells.

Why should you be careful about string concatenation (+) operator in loops?

Concatenation of two Strings If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.


1 Answers

While there might be usecases where you build a prepared statement by string-concatenation before compiling it, it is always bad practice to insert query-parameters using string-concatenation for two reasons:

  1. Performance: When using a prepared statement the query-syntax has to be parsed only once and the access-path has to be calculated only once for each distinct query-type. When building statements by string-concatenation parsing and optimizing has to be done for each execution of the query.
  2. Security: Using string-concatenation with data provided by the user is always prone to SQL-injection-attacks. Suppose you got a statement:

    query = "select secret_data from users where userid = '" + userid_param + "'";  
    

And imagine someone sends a userid_param containing "' OR 1=1;"...

This way the only way to defend is doing 100% correct input-sanitation which might be quite hard to get right depending on the language used. When using prepared statements with a properly implemented driver the driver will isolate the statement form the query-parameters so nothing will be mixed up.

like image 93
piet.t Avatar answered Nov 15 '22 11:11

piet.t