码迷,mamicode.com
首页 > 其他好文 > 详细

回调函数的使用

时间:2016-09-08 23:02:25      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

package com.huawei.common;

import java.sql.ResultSet;
import java.sql.SQLException;


/**
* 回调函数
* @author Administrator
*
*/
public interface CallBack {

void execute(ResultSet rs) throws SQLException;

}

 

package com.huawei.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.huawei.common.CallBack;
import com.huawei.po.City;
import com.huawei.po.Province;
import com.huawei.utils.DBUtil;


public class CascadeDAO2 {

public void findAll(String sql,Object[] params,CallBack callBack){
Connection connection = DBUtil.getConnection();

PreparedStatement ps = null;

ResultSet rs = null;

try {
ps = connection.prepareStatement(sql);
if(params!=null && params.length>0){
for(int i=0;i<params.length;i++){
//设置参数
ps.setObject(i+1, params[i]);
}
}
rs = ps.executeQuery();

//需要动态的加入一段代码执行
callBack.execute(rs);

} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs,ps,connection);
}
}

public List<Province> findAllProvince(){

final List<Province> provinces = new ArrayList<Province>();
//final String [] values = new String[]{""};
//final String a = "123";

//String s = "select * from city where provinceID=?"; new Object[]{}

String sql = "SELECT * FROM province";
this.findAll(sql, null,new CallBack() {

@Override
public void execute(ResultSet rs) throws SQLException {

while(rs.next()){
provinces.add(new Province(rs.getInt("provinceID"), rs.getString("province")));
}
//String abc = "lsi123";
//values[0] = abc;
}
});

return provinces;
}

public List<City> findCityByProvinceID(Integer id){
final List<City> cities = new ArrayList<City>();
String sql = "select * from city where provinceID=?";
this.findAll(sql, new Object[]{id}, new CallBack() {

@Override
public void execute(ResultSet rs) throws SQLException {
while(rs.next()){
cities.add(new City(rs.getInt("cityID"),rs.getString("city")));
}
}
});
return cities;
}

public static void main(String[] args) {
System.out.println(new CascadeDAO2().findAllProvince().size());
System.out.println(new CascadeDAO2().findCityByProvinceID(510000).size());

}

}

 

回调函数的使用

标签:

原文地址:http://www.cnblogs.com/hwgok/p/5854587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!