文件包含:
1、主类:SimpleJDBCTemplate
2、辅助类:ConnectionUtils 连接数据库
ResultSetHandler<T> 使用泛型定义处理结果集的接口
Java代码
SimpleJdbcTemplate 源代码:
package com.cpit.work.util.database;
/*
* 模板方法+回调(内部匿名类)的数据处理工具
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SimpleJdbcTemplate {
public static <T> T query(String queryString, ResultSetHandler<T> rsHandler) {
Connection connection = null;
PreparedStatement stmt = null;
try {
connection = ConnectionUtils.getInstance().getConnectionion(); // get a db connection.
stmt = connection.prepareStatement(queryString);
ResultSet rs = stmt.executeQuery();
return rsHandler.handle(rs);
} catch (SQLException ex) {
close(stmt); // close the statement
release(connection); // release connection
throw new RuntimeException("An sql exception occurred.", ex); // rethrow a runtime exception
} finally {
close(stmt); // close the statement
release(connection); // release connection
}
}
private static void release(Connection conn) {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void close(Statement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ConnectionUtils 源代码:
package com.cpit.work.util.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionUtils {
private final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
private final String URL = "jdbc:oracle:thin:@***.***.***.***:1521:****";
private final String USERNAME = "zj**";
private final String PASSWORD = "zj**";
private ConnectionUtils(){}
private static class DataBaseHolder{
private static final ConnectionUtils instance = new ConnectionUtils();
}
public static ConnectionUtils getInstance(){
return DataBaseHolder.instance;
}
public Connection getConnectionion() {
Connection conn = null;
try {
Class.forName(ORACLE_DRIVER);
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
ResultSetHandler<T> 源代码:
package com.cpit.work.util.database;
import java.sql.ResultSet;
public interface ResultSetHandler<T> {
public T handle(ResultSet rs);
}
使用代码:
Map<String,String> map = SimpleJdbcTemplate.query(sql, new ResultSetHandler<Map<String,String>>(){
public Map<String,String> handle(ResultSet rs){
Map<String,String> data = new HashMap<String,String>();
try {
while (rs.next()) {
String key = rs.getString("key");
String value = rs.getString("value");
data.put(key, value);
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
if(rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return data;
}
});