1、數據庫鏈接工具類 java
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 = "username";
private final String PASSWORD = "password";
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;
}
} sql
2、處理ResultSet結果集的公共接口 數據庫
import java.sql.ResultSet;
public interface ResultSetHandler<T> {
public T handle(ResultSet rs);
} oracle
3、SimpleJdbcTemplate主工具類 工具
import java.sql.Connection; spa
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(); stmt = connection.prepareStatement(queryString,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); 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); } 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(); } } }