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

使用Spring的JdbcTemplate和BeanPropertyRowMapper完成的JDBC
先道要加上两个包:Spring2.5下面的:?spring.jar和commons-logging.jar
我用的DBCP数据源,Connection工具类我就没写了
具体的实例说明:
?
public?class?StuDaoImple?implements?StuDaointer?{
?
????private?JdbcTemplate?jdbctemp?=?null;
?
????public?StuDaoImple()?{
???????jdbctemp?=?new?JdbcTemplate(SQLConnUtil.getDataSource());
????}
?
????//?所有添,删,改的方法都可以用jdbctemp.update();方法
????public?void?addStu(Stu?stu)?{
???????String?sql?=?"insert?into?stu?values(?,?,?)";
???????Object[]?obj?=?new?Object[]?{?stu.getSname(),?stu.getSsex(),new?java.sql.Date(stu.getSbrith().getTime())?};
???????jdbctemp.update(sql,?obj);//?可以传两个参数,第一个参数是SQL语句,第二个参数是SQL语句的参数值
????}
????public?void?delStu(int?sid)?{
???????String?sql?=?"delete?stu?where?s_id="?+?sid;
???????jdbctemp.update(sql);//?可以传一个参数,就是没有参数的SQL语句
????}
?
????public?void?updStu(Stu?stu)?{
???????String?sql?=?"update?stu?set?s_name=?,s_sex=?,s_brith=??where?s_id=?";
???????Object[]?obj?=?new?Object[]?{?stu.getSname(),?stu.getSsex(),new?java.sql.Date(stu.getSbrith().getTime()),?stu.getSid()?};
???????jdbctemp.update(sql,?obj,?new?int[]?{?Types.VARCHAR,?Types.VARCHAR,Types.DATE,?Types.INTEGER?});
???????//?可以传两个参数,第一个参数是SQL语句,第二个参数是SQL语句的参数值,第三个参数是SQL语句参数值的SQL类型
????}
????//查询1
????public?List?getAllStu()?{
???????String?sql="select?s_id,s_name,s_sex,s_brith?from?stu";
???????List?list=jdbctemp.query(sql,?new?RowMapper(){
?
???????????public?Object?mapRow(ResultSet?arg0,?int?arg1)?throws?SQLException?{
??????????????Stu?stu=new?Stu();
??????????????if(arg0!=null){
??????????????????stu.setSid(arg0.getInt("s_id"));
??????????????????stu.setSname(arg0.getString("s_name"));
??????????????????stu.setSsex(arg0.getString("s_sex"));
??????????????????stu.setSbrith(arg0.getDate("s_brith"));
??????????????}
??????????????return?stu;
???????????}
???????????
???????});
???????return?list;
????}
????
????//查询2
????public?List?getAllStu(int?id)?{
???????String?sql="select?s_id,s_name,s_sex,s_brith?from?stu?where?s_id<?";
???????Object[]?obj=new?Object[]{id};
???????//使用内部类
???????List?list=jdbctemp.query(sql,obj,new?RowMapper(){
?
???????????public?Object?mapRow(ResultSet?arg0,?int?arg1)?throws?SQLException?{
??????????????Stu?stu=new?Stu();
??????????????if(arg0!=null){
??????????????????stu.setSid(arg0.getInt("s_id"));
??????????????????stu.setSname(arg0.getString("s_name"));
??????????????????stu.setSsex(arg0.getString("s_sex"));
??????????????????stu.setSbrith(arg0.getDate("s_brith"));
??????????????}
??????????????return?stu;
???????????}
???????????
???????});
???????return?null;
????}
????//查询方式3(查询一个对象)
????public?Stu?getOneStu(int?id)?{
???????String?sql="select?s_id?as?sid,s_name?as?sname,s_sex?as?ssex,s_brith?as?sbrith?from?stu?where?s_id=?";
???????Object[]?obj=new?Object[]{id};