Use prepared statements and variable bindings to use JDBC drivers in Java

I'm using it

>JDBC template enables JDBC to connect to a MySQL Database > prepared statements to protect itself from SQL injection attacks as much as possible > you need to accept user requests to sort data in more than a dozen different columns > the following statements

jdbcTemplate.query("SELECT * FROM TABLE1 ORDER BY ? ?",colName,sortOrder);

Of course, this does not work, because variable binding should not specify column names, but the parameter values of expressions in queries

So... How do people solve this problem? Just sorting in Java code seems to be a simple solution, but because I get a variable string that can be sorted, a variable tells me the sorting order This is the ugly number of comparator conditions This seems to be a common problem that should solve its common pattern?

Solution

Placeholder? It can only be used for parameter values, but not for columns and sort order directions So the standard way to do this is to point out Here is a query that uses string #format () or something similar to append your column name and order value to your query

Another option is to use spring data JPA, where you can assign parameters as parameters to an instance of type sort, which can contain all the necessary information for sorting the database

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>