1. 程式人生 > >jdbcTemplate操作資料庫的DDL語句

jdbcTemplate操作資料庫的DDL語句

jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");

使用JdbcTemplate進行查詢時,可以使用queryForXXX()等方法,例如使用queryForInt()方法傳回user表格中的資料數目: jdbcTemplate.quertForInt("select count(*) from user"); 也可以使用queryForObject()傳回一個查詢後的物件,例如傳回一個String物件:

String name=(String)jdbcTemplate.queryForObject("selcet name from user where id=?",new Object[]{id},java.lang.String.class);)

單獨查詢某個資料

並賦值給特定物件時:

    public BaseObj getBaseObj(final int ID) {
        String sql = "select * from " + DB_TABLE_NAME + " where NewsId=" + ID;
        BaseObj obj =(BaseObj) getJdbcTemplate().query(sql,new ResultSetExtractor(){
            public Object extractData(ResultSet rs) throws SQLException,DataAccessException {
                if (rs.next()) {
                    NewsObj news = new NewsObj();
                    news.setID(rs.getInt("NewsID"));
                    news.setTitle(rs.getString("NewsTitle"));
                    news.setBigClass(rs.getInt("BigClassId"));
                    news.setNewsContent(rs.getString("NewsContent"));
                    news.setNewsKey(rs.getString("NewsKey"));
                    news.setNewsAuthor(rs.getString("NewsAuthor"));
                    news.setImg(rs.getBoolean("isImg"));
                    news.setNewsFrom(rs.getString("NewsFrom"));
                    return news;
                }
                return null;
            }
        });
       return obj;

    }

上面兩個例子都是傳回單獨一筆資料,如果要傳回多筆資料,則可以使用queryForList()方法

例如:
List rows=jdbcTemplate().queryForList("select * from user where id="+id.intValue()); 傳回的list中包括的是map物件,每個map物件代表查詢結果中的一筆資料,每筆資料包括多個欄位,要取得欄位中的值,就要使用欄位名作為key,
例如:
    Iterator it=rows.iterator();
    while(it.hasNext()){
        Map result=(Map)it.next();
        System.out.println(userMap.get("id"));
        System.out.println(userMap.get("name"));
        System.out.println(userMap.get("age"));
     }

在查詢的同時,你可以在返回結果之前先進行一些處理,這就要實現RowCallbackHandler介面

public User find(Integer id){
    final User user=new User();
    jdbcTemplate.query("select * from user where id=?",new Object[]{id},
                                     new RowCallBackHandler(){
                                           public void proccessRow(ResultSet rs){ 
                                                 user.setId(new Integer(rs.getInt("id")));
                                                 uset.setName(rs.getString("name"));    
                                            }});
    return user;
}

如果一次要返回多個查詢結果物件,則可以實現RowMapper介面

public class UserRowMapper implements RowMapper{
        public Object MapRow(ResultSet rsmint rowNum) throws SQLException{
                User user=new User();
                user.setId(new Integer(rs.getInt("id")));
                user.setName(rs.getString("name"));
                return user;
       } 
}

使用RowMapper查詢單筆資料

public User find(Integer id){
         User user=(User)jdbcTemplate.queryForObject("select * from user where id=?",new Object[]{id},new UserRowMapper());
          return user;
}

使用RowMapper查詢多筆資料

class UserRowMapper implements RowMapper {
         public Object mapRow(ResultSet rs,int index) throws SQLException 
         {
             User u = new User();
             u.setId(rs.getString(”ID”));
             u.setName(rs.getString(”Name”));
             u.setPassword(rs.getString(”Password”));
             return u;
         }
     }
public List select(String where)
    {
        List list;        
        String sql = "select * from admin "+where;        
        list = jdbcTemplate.query(sql,new RowMapperResultReader(new UserRowMapper()));
        return list;
    }

傳回的users物件中,包括了從資料庫查詢出來的結果,並已經封裝成user物件

JdbcTemplate語句使用:

1、使用JdbcTemplate的execute()方法執行SQL語句

程式碼
jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");

2、如果是UPDATE或INSERT,可以用update()方法。

程式碼
jdbcTemplate.update("INSERT INTO USER VALUES('"   
            + user.getId() + "', '"   
            + user.getName() + "', '"   
            + user.getSex() + "', '"   
            + user.getAge() + "')");  

3、帶引數的更新


程式碼
jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?", new Object[] {name, id});


程式碼
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", new Object[] {user.getId(), user.getName(), user.getSex(), user.getAge()});  

4、使用JdbcTemplate進行查詢時,使用queryForXXX()等方法


程式碼
int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");


程式碼
String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id = ?", new Object[] {id}, java.lang.String.class);


程式碼
List rows = jdbcTemplate.queryForList("SELECT * FROM USER");


程式碼
List rows = jdbcTemplate.queryForList("SELECT * FROM USER");    
Iterator it = rows.iterator();    
while(it.hasNext()) {    
    Map userMap = (Map) it.next();    
    System.out.print(userMap.get("user_id") + "\t");    
    System.out.print(userMap.get("name") + "\t");    
    System.out.print(userMap.get("sex") + "\t");    
    System.out.println(userMap.get("age") + "\t");    
}  

JdbcTemplate將我們使用的JDBC的流程封裝起來,包括了異常的捕捉、SQL的執行、查詢結果的轉換等等。spring大量使用Template Method模式來封裝固定流程的動作,XXXTemplate等類別都是基於這種方式的實現。 
除了大量使用Template Method來封裝一些底層的操作細節,spring也大量使用callback方式類回撥相關類別的方法以提供JDBC相關類別的功能,使傳統的JDBC的使用者也能清楚瞭解spring所提供的相關封裝類別方法的使用。

JDBC的PreparedStatement


程式碼
final String id = user.getId();    
final String name = user.getName();    
final String sex = user.getSex() + "";    
final int age = user.getAge();    
   
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",    
                     new PreparedStatementSetter() {    
                         public void setValues(PreparedStatement ps) throws SQLException {    
                             ps.setString(1, id);    
                             ps.setString(2, name);              
                             ps.setString(3, sex);    
                             ps.setInt(4, age);    
                         }    
                     });   


程式碼
final User user = new User();    
jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",    
                    new Object[] {id},    
                    new RowCallbackHandler() {    
                        public void processRow(ResultSet rs) throws SQLException {    
                            user.setId(rs.getString("user_id"));    
                            user.setName(rs.getString("name"));    
                            user.setSex(rs.getString("sex").charAt(0));    
                            user.setAge(rs.getInt("age"));    
                        }    
                    });   

程式碼
class UserRowMapper implements RowMapper {    
    public Object mapRow(ResultSet rs, int index) throws SQLException {    
        User user = new User();    
   
        user.setId(rs.getString("user_id"));    
        user.setName(rs.getString("name"));    
        user.setSex(rs.getString("sex").charAt(0));    
        user.setAge(rs.getInt("age"));    
   
        return user;    
    }    
}    
   
public List findAllByRowMapperResultReader() {    
    String sql = "SELECT * FROM USER";    
    return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));    
}   

在getUser(id)裡面使用UserRowMapper


程式碼
public User getUser(final String id) throws DataAccessException {    
    String sql = "SELECT * FROM USER WHERE user_id=?";    
    final Object[] params = new Object[] { id };    
    List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper()));    
   
    return (User) list.get(0);    
}  

網上收集 
org.springframework.jdbc.core.PreparedStatementCreator 返回預編譯SQL 不能於Object[]一起用


程式碼
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {    
return con.prepareStatement(sql);    
}  

1.增刪改 
org.springframework.jdbc.core.JdbcTemplate 類(必須指定資料來源dataSource)


程式碼
template.update("insert into web_person values(?,?,?)",Object[]);  


程式碼
template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){ 匿名內部類 只能訪問外部最終區域性變數    
   
public void setValues(PreparedStatement ps) throws SQLException {    
ps.setInt(index++,3);    
});  

org.springframework.jdbc.core.PreparedStatementSetter 介面 處理預編譯SQL


程式碼
public void setValues(PreparedStatement ps) throws SQLException {    
ps.setInt(index++,3);    
}  

2.查詢JdbcTemplate.query(String,[Object[]/PreparedStatementSetter],RowMapper/RowCallbackHandler) 
org.springframework.jdbc.core.RowMapper 記錄對映介面 處理結果集


程式碼
public Object mapRow(ResultSet rs, int arg1) throws SQLException {   int表當前行數    
person.setId(rs.getInt("id"));    
}    
List template.query("select * from web_person where id=?",Object[],RowMapper);  

org.springframework.jdbc.core.RowCallbackHandler 記錄回撥管理器介面 處理結果集


程式碼
template.query("select * from web_person where id=?",Object[],new RowCallbackHandler(){    
public void processRow(ResultSet rs) throws SQLException {    
person.setId(rs.getInt("id"));    
});