Package Com.huawei.common;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
/**
* Callback function
* @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++) {
Setting parameters
Ps.setobject (i+1, params[i]);
}
}
rs = Ps.executequery ();
Need to dynamically add a piece of code execution
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 the 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 (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 ());
}
}
Use of callback functions in Java