
Passing Parameter in JDBCTemplate
The previous example has just retrieved all data from the table and prints on screen. But we always retrieve the conditional data based on some criteria from the database in the real world. The following java class will fetch only the id =1 record from the Customer table.
package com.visualbuilder.DAO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public final class ParameterPassing {
public static void main(String[] args) throws Exception {
BeanFactory ctx = new ClassPathXmlApplicationContext(
"com/visualbuilder/DAO/bean.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
List customerList = jdbcTemplate.query("select id,name from customer where id=?",
new Object[]{Long.valueOf(1)}, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum)
throws SQLException, DataAccessException {
CustomerBean cusomter = new CustomerBean();
cusomter.setId(rs.getString(1));
cusomter.setName(rs.getString(2));
return cusomter;
}
});
System.out.println("The Size of the data retreived :-");
for (int i = 0; i < customerList.size(); i++) {
CustomerBean cust = (CustomerBean) customerList.get(i);
System.out.println("ID is :- " + cust.getId());
System.out.println("Name is :- " + cust.getName());
}
}
}
Output :- The following result will be displayed on screen.
The retreived data is as follows:-
ID is :- 1
Name is :- VisualBuilder
Java Discussion
- - Difference between BMT an
- - Replace getParameterValue
- - Interviewing Next week -
- - Sudoku solver
- - Setting tab order in swin



