본문 바로가기
프로그램/Etc

[Spring] Spring JDBC – JdbcTemplate 사용 예제

by 로드러너 2014. 2. 16.
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

private JdbcTemplate jdbcTemplate;

jdbcTemplate = new JdbcTemplate(dataSource);

 

 

1. select 문의 결과로 정수값 반환

     int cnt = jdbcTemplate.queryForInt(“select count(*) from test”);

 

2. select 문에 변수를 바인딩해서 사용

     int cnt = jdbcTemplate.queryForInt(“select count(*) from test where name = ?”, new Object[]{“강”});

 

3. select 문의 결과로 문자열을 반환

     String name = (String) jdbcTemplate.queryForObject(“select name from test where seq_no = ?”, new Object[]{new Long(1)}, String.class);

 

4. select 문의 결과로 한개의 레코드 값을 맵핑

     Member mem = (Member) jdbcTemplate.queryForObject(

                     “select name, age from test where seq_no = ?”,

                     new Object[]{new Long(1)},

                     new RowMapper(){

                            public Object mapRow(ResultSet rs, int rowCnt) throws SQLException{

                                  Member mem = new Member();

                                  mem.setName(rs.getString(“name”));

                                  mem.setAge(rs.getInt(“age”));

                                  return mem;

                            }

                       });

 

5. select 문의 결과로 한개 이상의 레코드를 집합객체에 매핑

Collection mems = jdbcTemplate.query(

          “select name, age from test”,

          new RowMapper(){

                public Object mapRow(ResultSet rs, int rowCnt) throws SQLException{

                         Member mem = new Member();

                         mem.setName(rs.getString(“name”));

                         mem.setAge(rs.getInt(“age”));

                        return mem;

                }

          });

 

6. select 문의 결과로 한개 이상의 레코드를 집합객체에 매핑

     public Collection allMems(){

          return this.jdbcTemplate.query(“select name, age from test”, new MemMapper());

     }

 

     private static final class MemMapper implements RowMapper{

          public Object mapRow(ResultSet rs, int rowCnt) throws SQLException{

               Member mem = new Member();

               mem.setName(rs.getString(“name”));

               mem.setAge(rs.getInt(“age”));

               return mem;

          }

     }

 

7. insert 예제

     jdbcTemplate.update(“insert into test(name, age) values(?, ?),

                                                  new Object[]{“강”, new Long(30)});

 

8. delete 예제

     jdbcTemplate.update(“delete from test”);

 

9. DLL 예제

     jdbcTemplate.execute(“create table test(name varchar2(50), age integer)”);

 

 

 

* 참조 : 다미네 놀이터