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?
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.
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.
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.
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.
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:
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.
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