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());

}

}