---
title: "spring中使用JdbcTemplate的三种方式"
author: "cookieandsession"
date: "2013-07-17T16:57:23Z"
tags: []
categories: ["行业应用"]
slug: "spring-jdbctemplate"
draft: false
lastmod: "2013-07-17T17:02:46Z"
id: 1908514
url: "https://cookieandsession.iteye.com/blog/1908514"
---

1、使用Jdbc Template(JdbcTemplate模板类)
2、使用命名参数jdbc模板NamedParameterJdbcTemplate
3、使用基于jdk1.5的简单jdbc模板SimpleJdbcTemplate

```java
public List<Customer> findCustomerByName(String name) {
		String sql = "select id,name,age from customers where name=?";
		return jdbcTemplate.query(sql, new Object[]{name}, new RowMapper(){
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				Customer customer = new Customer();
				customer.setId(rs.getInt("id"));
				customer.setName(rs.getString("name"));
				customer.setAge(rs.getInt("age"));
				return customer;
			}});
	}
```

```java
public List<Customer> findCustomerByName(String name) {
		String sql = "select id,name,age from customers where name=:name";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", name);
		return jdbcTemplate.query(sql, map, new RowMapper(){
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				Customer customer = new Customer();
				customer.setId(rs.getInt("id"));
				customer.setName(rs.getString("name"));
				customer.setAge(rs.getInt("age"));
				return customer;
			}});
	}
```

```java
String sql = "select id,name,age from customers where name=?";
		return jdbcTemplate.query(sql, new ParameterizedRowMapper<Customer>(){
			public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
				Customer customer = new Customer();
				customer.setId(rs.getInt("id"));
				customer.setName(rs.getString("name"));
				customer.setAge(rs.getInt("age"));
				return customer;
			}}, name);
```