// 定義回呼函式
public interface Job<T> {
public void callback(T res);
}
-----------------------------------------------------------
// 發出 ajax需求
public class T_1 {
public StringBuilder res = new StringBuilder("hi");
public Inner job = new Inner();
public void setRes(StringBuilder res) {
this.res = res;
}
//=======================
// 相當於 js callback
class Inner implements Job<StringBuilder> {
public void callback(StringBuilder _res) {
setRes(_res);
System.out.println(res);
}
}
//=================================
public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable db = null;
T_1 t = new T_1();
try {
db = new Mysql_1("xd702g3", "SELECT * FROM paris_roomtype", t.job);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread th_1 = new Thread(db);
th_1.start();
}
}
-----------------------------------------------------------
// ajax 處理
public class Mysql_1 implements Runnable {
private String db_path;
private String db_host = "jdbc:mysql://localhost/";
private String db_arg = "useUnicode=true&characterEncoding=Utf8";
private String username = "xd702g3";
private String password = "xd702g3";
private Connection con = null;
private Statement stat = null;
private ResultSet rs = null;
private String sql = null;
public StringBuilder res = new StringBuilder();
public Job<StringBuilder> job = null;
// ==========================================================================
public Mysql_1(String table, String sql,Job<StringBuilder> job) throws Exception {
// TODO Auto-generated constructor stub
db_path = db_host + table + "?" + db_arg;
this.sql = sql;
this.job = job;
connect();
}
// ==========================================================================
private void connect() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(db_path, username, password);
stat = con.createStatement();
}
// ==========================================================================
private StringBuilder query() throws Exception {
rs = stat.executeQuery(sql);
while (rs.next()) {
var a = rs.getInt(1);
var b = rs.getString(2);
// System.out.println(a + "\t" + b);
res.append(b);
}
return res;
}
// ==========================================================================
@Override
public void run() {
try {
var res = query();
job.callback(res);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ==========================================================================
}