1、yml配置
warning:
oracle:
url: xxx
username: xxx
password: xxx
driverClassName: oracle.jdbc.driver.OracleDriver
2、完整代码
public class Test {
@Value("${warning.oracle.url:}")
private String url;
@Value("${warning.oracle.username:}")
private String username;
@Value("${warning.oracle.password:}")
private String password;
@Value("${warning.oracle.driverClassName:}")
private String driverClassName;
public List<CheckResult> findCheckList( Date startTime ) {
// 1. 建立连接
Connection conn = getConnection();
//PreparedStatement 适用于预编译的 SQL 语句,可以提高性能并防止 SQL 注入
PreparedStatement stmt = null;
//sql返回的结果集
ResultSet resultSet = null;
List<CheckResult> checkIdList = new ArrayList<>();
try {
// 2. 创建Statement对象
String sql = "SELECT START_TIME, CHECK_ID FROM check_result WHERE START_TIME > ?";
stmt = conn.prepareStatement(sql);
log.info("oracle-getCheckIdList 查询开始");
// 3. 设置参数
Timestamp start = new Timestamp(startTime.getTime());
stmt.setTimestamp(1, start);
// 4. 执行查询
resultSet = stmt.executeQuery();
// 5. 处理结果
while (resultSet.next()) {
CheckResult checkResult = new CheckResult();
checkResult.setCheckId(resultSet.getString("CHECK_ID"));
checkResult.setStartTime(resultSet.getTimestamp("START_TIME"));
checkIdList.add(checkResult);
}
log.info("oracle-getCheckIdList 查询成功,共查询成功{}条", checkIdList.size());
return checkIdList;
} catch (Exception e) {
log.error("oracle-getCheckIdList 报错:{}", e);
throw new RuntimeException(e);
} finally {
// 6. 关闭资源
close(resultSet, stmt);
}
}
/**
* 建立连接
* @return
*/
private Connection getConnection() {
Connection conn = null;
try {
// 加载Oracle JDBC驱动
Class.forName(driverClassName);
// 建立连接
conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (Exception e) {
log.error("获取Oracle数据库连接报错:{}", e);
throw new RuntimeException(e);
}
}
/**
* 关闭资源
* @param rs
* @param stmt
*/
private void close(ResultSet rs, PreparedStatement stmt) {
// 关闭资源
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}