package template;
import java.sql.Connection;
import java.sql.ResultSet;
/**
* Created by marcopan on 17/9/26.
*/
public abstract class QueryRunner {
public abstract Connection createConnection();
public abstract String createSQL();
public abstract ResultSet runSQL(Connection conn, String sql);
public ResultSet run() throws Exception {
Connection conn = null;
String sql = "";
try {
conn = this.createConnection();
sql = this.createSQL();
return runSQL(conn, sql);
} finally {
if (conn != null) {
conn.close();
}
}
}
}
package template;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Created by marcopan on 17/9/26.
*/
public class OracleQueryRunner extends QueryRunner {
@Override
public Connection createConnection() {
System.out.println("createConnection from OracleQueryRunner");
return null;
}
@Override
public String createSQL() {
return "createSQL from OracleQueryRunner";
}
@Override
public ResultSet runSQL(Connection conn, String sql) {
System.out.println("runSQL from OracleQueryRunner");
Statement st = null;
try {
st = conn.createStatement();
return st.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return null;
}
}
待补充:spring中的JdbcTemplate中用到的模板模式