日期:2014-05-16  浏览次数:20457 次

Spring JDBC模版基本操作示例 (转)
jdbc 模板基本操作的基本步骤:
1 数据库连接,返回全局使用的datasorce;
2 jdbc模板建立,全局使用,依赖database;
3自定义dao,对应一个配置文件(jdbcTemplate 属性 ) 依赖 jdbc模板。
4 控制通过 getBean对像得到jdbcTemplate.

  user表
+-------+-------------+------+-----+---------+----------------+

| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(15)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(15) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+


Insert:

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class TestDAOjdbc extends JdbcDaoSupport{

String tableName="user";
          String sql = "insert into " + tableName+"(name)"+ "values(?)";

JdbcTemplate jt=getJdbcTemplate();

  jt.update(sql,
                 new PreparedStatementSetter(){
                        public void setValues(PreparedStatement ps) throws SQLException{
                            ps.setString(1,"coco");
                       }
                  }                               
               );     
//删除
    public void deldb(){
        JdbcTemplate jt=getJdbcTemplate();
        String sql="DELETE FROM user WHERE id=?";
        jt.update(sql, new PreparedStatementSetter(){
            public void setValues(PreparedStatement ps)throws SQLException{
                  ps.setInt(1,5);
            }
        });
}

//查询数据库多少行 信息 --使用queryForInt()方法传回user表格中的数据数目
public int getCount(){
    JdbcTemplate jt=getJdbcTemplate();
    String sql="select count(*)from user";
    int count=jt.queryForInt(sql);
    return count;
}
//查询指定名字信息--使用queryForObject()传回一个查询后的结果对象,例如传回一个String对象
public String getName(){
    JdbcTemplate jt=getJdbcTemplate();
    String sql="select name from user where id=10";
    String name=(String)jt.queryForObject(sql, java.lang.String.class);
    return name;
}

//将查询的多项数据信息填写到user Bean中
public List findUser(){
    JdbcTemplate jt=getJdbcTemplate();
    String sql="select * from user";
    List list