Select records from database with JdbcTemplate

With this example we are going to demonstrate how to select records from a database using the JdbcTemplate class provided by the Spring Framework. The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving application code to provide SQL and extract results. This class executes SQL queries or updates, initiating iteration over ResultSets and catching JDBC exceptions. In short, to select records from a database using the JdbcTemplate class you should:

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.enterprise;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class SelectRecordsFromDatabaseWithJdbcTemplate {
	
	private static final String driverClassName = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost/companydb";
	private static final String dbUsername = "jcg";
	private static final String dbPassword = "jcg";
	private static final String selectSql = "SELECT * FROM employee";
	private static DataSource dataSource;
	
	public static void main(String[] args) throws Exception {
	
		dataSource = getDataSource();
		
		JdbcTemplate template = new JdbcTemplate(dataSource);
		
		List<Map<String, Object>> employees = template.queryForList(selectSql);
		
		if (employees!=null && !employees.isEmpty()) {
			
			for (Map<String, Object> employee : employees) {
				
				for (Iterator<Map.Entry<String, Object>> it = employee.entrySet().iterator(); it.hasNext();) {
					Map.Entry<String, Object> entry = it.next();
					String key = entry.getKey();
					Object value = entry.getValue();
					System.out.println(key + " = " + value);
				}
				
				System.out.println();
				
			}
			
		}
		
	}
	
	public static DriverManagerDataSource getDataSource() {
  DriverManagerDataSource dataSource = new DriverManagerDataSource();
  dataSource.setDriverClassName(driverClassName);
  dataSource.setUrl(url);
  dataSource.setUsername(dbUsername);
  dataSource.setPassword(dbPassword);
  return dataSource;
    }
}
CREATE TABLE `companydb`.`employee` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `surname` VARCHAR(45) NOT NULL,
  `title` VARCHAR(45) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);

Output:

id = 1
name = John
surname = Black
title = Software developer
created = 2011-11-20 12:13:24.0

id = 2
name = Tom
surname = Green
title = Project Manager
created = 2011-11-20 12:13:24.0

 
This was an example of how to select records from a database using the JdbcTemplate class provided by the Spring Framework.

Exit mobile version