Is there a better way to execute this SQL statement in Spring using JdbcTemplate? - spring

I have an SQL statement to select a BRAND_NAME based on an input parameter. The code goes something like this:
public ResponseEntity<List<Map<String, Object>>> getBrand(String brandName){
sql = "SELECT BRAND_NAME AS \"brandName\" FROM BRAND_E WHERE LOWER(BRAND_NAME) LIKE '%" + brandName + "%'";
return new ResponseEntity<List<Map<String, Object>>>(jdbc.queryForList(sql), HttpStatus.OK);
}
I've found out that this can probably cause SQL injection attacks, so I was wondering how to code this better.

Yes.If you directly use the request param on your sql it can lead to SQL injection attacks. We can always go with the prepared statement by adding a placeholder to where the values must be added.
Use queryForList(String sql, Object... args) or queryForList(String sql, Object[] args, Class<T> elementType)
Eg:-
String employeeId= "1";
String sql = "select id,name,address from employee where id = ?";
getJdbcTemplate(). queryForList(sql, new Object[]{employeeId}, Employee.class);

Related

Query to check if the record exists in Spring Jdbc Template

I am fairly new to spring ,I am looking to check if a certain email id exists in database or not , using Spring Jdbc Template ,I looked here but could'nt find the proper answer .I am looking something like ,SELECT count(*) from table where email=?
Any help will be appreciated.
You can do something as below if you are using jdbctemplate and new version of spring
private boolean isEmailIdExists(String email) {
String sql = "SELECT count(*) FROM table WHERE email = ?";
int count = jdbcTemplate.queryForObject(sql, new Object[] { email }, Integer.class);
return count > 0;
}
queryForObject method of jdbcTemplate accepts the sql query as the first parameter, second argument is an array of objects for the sql query place holders and the third argument is the expected return value from the sql query.
In this case we only have one place holder and hence I gave the second argument as new Object[] { email } and the result we are expecting is a count which is a Integer and hence I gave it as Integer.class
I kind of got this answer from https://www.mkyong.com/spring/jdbctemplate-queryforint-is-deprecated/
You can go through it if you are interested.
private boolean isEmailIdExists(String email) {
return jdbcTemplate.queryForObject("SELECT EXISTS(SELECT FROM table WHERE email = ?)", Boolean.class, email);
}
http://www.postgresqltutorial.com/postgresql-exists/

selecting from data base according user inputs

servlets, oracle SQL developer .. i want to select data from database but accoeding to user inputs .. here is my code
public ResultSet f_items(Connection conn,String price) throws SQLException {
String query = "select * from items where price=? ";
Statement st=conn.createStatement();
ResultSet set=st.executeQuery(query);
return set;
}
the price is a column in the table ... but this code gives me an SQL exception which is
: ORA-01008: not all variables bound
any help ??
You do not set the expected price on the statement. It should look sth. like this:
....
String query = "select * from items where price='" + price + "'";
ResultSet set=st.executeQuery(query);
EDIT: like Multisync suggested, but with an explanation :)
String query = "select * from items where price=? ";
PreparedStatement st=conn.prepareStatement(query);
st.setString(1, price);
ResultSet set=st.executeQuery(query);
Why is using a prepared statement better?
concatenating user input into DB queries is a recipe for disaster, known as SQL injection.
methods of PreparedStatement like setString will escape the string value for you, preventing SQL injection.
public ResultSet f_items(Connection conn,String price) throws SQLException {
String query = "select * from items where price=? ";
PreparedStatement st=conn.prepareStatement(query);
st.setString(1, price);
ResultSet set=st.executeQuery(query);
return set;
}

How to use prepared statement that returns resultset with jdbcTemplate in spring mvc 3?

Here is my code which uses jdbcTemplate
String SQL = "select branch from branchTable where branch_name = '" + branch + "'";
ArrayList<String> branchList = (ArrayList<String>) jdbcTemplateObject.query(SQL, new RowMapper() {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getString("city_desc");
}
});
return branchList;
Now i want to be able to use preparedstatement with a query like "select branch from branchTable where branch_name = ?"
How can i do that with jdbcTemplate ?
Examples i searched show demonstration on how to use it with update or insert query, but not with select query..
Please help.
JdbcTemplate has another query() method which takes arguments of the prepared statement as parameter:
jdbcTemplateObject.query(SQL, new Object[] {branchName}, new RowMapper() {...});
Note that:
SQL should be named sql
You should use List and not ArrayList. Nothing in the javadoc guarantees that an ArrayList is returned. And you shouldn't care about the concrete type of list returned.
You should use a RowMapper<String> and not a raw RowMapper.

How to make INSERT safer?

This is my method. As you can see I'm using native sql to execute INSERT queries.
public void addNews(String title, String content) {
Session session = null;
session = this.sessionFactory.getCurrentSession();
Query query = session
.createSQLQuery(
"INSERT INTO news VALUES(NULL,:title,:content,NULL)")
.setString("title", title).setString("content", content);
int updated = query.executeUpdate();
}
Is it safe? Or how can I improve my method?
Yes, setting values as parameters (setString() method) preventing from SQL-injections. Non secure sql-statement looks like this:
String query = "INSERT INTO news VALUES(NULL," + title + "," + content + ",NULL)";
Read more about SQL injections (and other types of vulnerabilities) you can here: https://www.owasp.org/index.php/SQL_Injection

Resultset Metadata from Spring JDBCTemplate Query methods

Is there any way I can get resultset object from one of jdbctemplate query methods?
I have a code like
List<ResultSet> rsList = template.query(finalQuery, new RowMapper<ResultSet>() {
public ResultSet mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs;
}
}
);
I wanted to execute my sql statement stored in finalQuery String and get the resultset. The query is a complex join on 6 to 7 tables and I am select 4-5 columns from each table and wanted to get the metadata of those columns to transform data types and data to downstream systems.
If it is a simple query and I am fetching form only one table I can use RowMapper#mapRow and inside that maprow method i can call ResultsetExtractor.extractData to get list of results; but in this case I have complex joins in my query and I am trying to get resultset Object and from that resultset metadata...
The above code is not good because for each result it will return same resultset object and I dont want to store them in list ...
Once more thing is if maprow is called for each result from my query will JDBCTemplate close the rs and connection even though my list has reference to RS object?
Is there any simple method like jdbcTemplate.queryForResultSet(sql) ?
Now I have implemented my own ResultSet Extractor to process and insert data into downstream systems
sourceJdbcTemplate.query(finalQuery, new CustomResultSetProcessor(targetTable, targetJdbcTemplate));
This CustomResultSetProcessor implements ResultSetExtractor and in extractData method I am calling 3 different methods 1 is get ColumnTypes form rs.getMetaData() and second is getColumnTypes of target metadata by running
SELECT NAME, COLTYPE, TBNAME FROM SYSIBM.SYSCOLUMNS WHERE TBNAME ='TABLENAME' AND TABCREATOR='TABLE CREATOR'
and in 3rd method I am building the insert statement (prepared) form target columntypes and finally calling that using
new BatchPreparedStatementSetter()
{
#Override
public void setValues(PreparedStatement insertStmt, int i) throws SQLException{} }
Hope this helps to others...
Note that the whole point of Spring JDBC Template is that it automatically closes all resources, including ResultSet, after execution of callback method. Therefore it would be better to extract necessary data inside a callback method and allow Spring to close the ResultSet after it.
If result of data extraction is not a List, you can use ResultSetExtractor instead of RowMapper:
SomeComplexResult r = template.query(finalQuery,
new ResultSetExtractor<SomeComplexResult>() {
public SomeResult extractData(ResultSet) {
// do complex processing of ResultSet and return its result as SomeComplexResult
}
});
Something like this would also work:
Connection con = DataSourceUtils.getConnection(dataSource); // your datasource
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(query); // your query
ResultSetMetaData rsmd = rs.getMetaData();
Although I agree with #axtavt that ResultSetExtractor is preferred in Spring environment, it does force you to execute the query.
The code below does not require you to do so, so that the client code is not required to provide the actual arguments for the query parameters:
public SomeResult getMetadata(String querySql) throws SQLException {
Assert.hasText(querySql);
DataSource ds = jdbcTemplate.getDataSource();
Connection con = null;
PreparedStatement ps = null;
try {
con = DataSourceUtils.getConnection(ds);
ps = con.prepareStatement(querySql);
ResultSetMetaData md = ps.getMetaData(); //<-- the query is compiled, but not executed
return processMetadata(md);
} finally {
JdbcUtils.closeStatement(ps);
DataSourceUtils.releaseConnection(con, ds);
}
}

Resources