dev/java 배포
java file read db 저장 #007
strange-dev
2025. 5. 1. 23:09
반응형
java file read to oracle save
텍스트 파일을 읽어 oracle 디비에 저장하겠습니다.
기존 소스에 추가된 소스입니다.
file에서 한 줄씩 읽어 oracle에 저장하는 소스입니다.
String oracleUrl = dbProps.getProperty("oracle.url");
String oracleUser = dbProps.getProperty("oracle.username");
String oraclePassword = dbProps.getProperty("oracle.password");
oracleConn = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
oracleConn.setAutoCommit(false);
String insertQuery = "INSERT INTO your_oracle_table (content) VALUES (?)";
oracleStmt = oracleConn.prepareStatement(insertQuery);
// 텍스트 파일 읽기 및 Oracle 테이블에 삽입
String textFilePath = dbProps.getProperty("textfile.path");
br = new BufferedReader(new FileReader(textFilePath));
String line= "";
int size = 0;
while ((line = br.readLine()) != null) {
oracleStmt.setString(1, line);
oracleStmt.executeUpdate();
size++;
}
oracleConn.commit();
System.out.println(textFilePath + "파일 읽기 및 Oracle 테이블에 insert 완료 - 건수 : " + size + ", 시간 : " + LocalDateTime.now());
oracleConn = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
- DriverManager.getConnection() 메서드를 사용하여 Oracle 데이터베이스에 연결
oracleConn.setAutoCommit(false);
- setAutoCommit(false) 메서드를 호출하여 데이터베이스의 자동 커밋 기능을 비활성화
oracleStmt = oracleConn.prepareStatement(insertQuery);
- SQL 쿼리(insertQuery)를 기반 PreparedStatement 객체 생성. PreparedStatement는 미리 컴파일된 SQL 문을 나타내며, 동일한 쿼리를 여러 번 실행할 때 성능 향상을 가져올 수 있습니다.
- 파라미터를 플레이스홀더(?)로 지정
oracleStmt.setString(1, line)
- 현재 읽은 line의 내용을 oracleStmt의 첫 번째 플레이스홀더(?)에 문자열 값으로 설정
oracleStmt.executeUpdate()
- 쿼리를 실행
전체 소스
- 특정 경로의 txt 파일을 읽어 한 줄씩 oracle에 저장하는 전체 소스입니다.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
private static final Properties dbProps = new Properties();
static {
try (InputStream input = Main.class.getClassLoader().getResourceAsStream("app.properties")) {
dbProps.load(input);
} catch (IOException ex) {
logger.error("app.properties 파일을 로드하는 데 실패했습니다.", ex);
throw new RuntimeException("설정 파일 로드 실패", ex);
}
}
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Runnable task = () -> {
Connection oracleConn = null;
PreparedStatement oracleStmt = null;
BufferedReader br = null;
try {
// Oracle 연결
String oracleUrl = dbProps.getProperty("oracle.url");
String oracleUser = dbProps.getProperty("oracle.username");
String oraclePassword = dbProps.getProperty("oracle.password");
oracleConn = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
oracleConn.setAutoCommit(false);
String insertQuery = "INSERT INTO your_oracle_table (content) VALUES (?)";
oracleStmt = oracleConn.prepareStatement(insertQuery);
// 텍스트 파일 읽기 및 Oracle 테이블에 삽입
String textFilePath = dbProps.getProperty("textfile.path");
br = new BufferedReader(new FileReader(textFilePath));
String line= "";
int size = 0;
while ((line = br.readLine()) != null) {
oracleStmt.setString(1, line);
oracleStmt.executeUpdate();
size++;
}
oracleConn.commit();
System.out.println(textFilePath + "파일 읽기 및 Oracle 테이블에 insert 완료 - 건수 : " + size + ", 시간 : " + LocalDateTime.now());
} catch (SQLException e) { logger.error("SQL Exception 발생", e); if (oracleConn != null) {try {oracleConn.rollback();} catch (SQLException ex) {logger.error("oracleStmt Exception 발생", ex);}}
} catch (IOException e) { logger.error("텍스트 파일 읽기 오류 발생", e); if (oracleConn != null) {try {oracleConn.rollback();} catch (SQLException ex) {logger.error("oracleStmt Exception 발생", ex);}}
} finally {
try { if (br != null) br.close(); } catch (IOException e) { logger.error("BufferedReader close Exception 발생", e); }
try { if (oracleStmt != null) oracleStmt.close(); } catch (SQLException e) { logger.error("oracleStmtText Exception 발생", e); }
try { if (oracleConn != null) oracleConn.close(); } catch (SQLException e) { logger.error("oracleConn Exception 발생", e); }
}
};
scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
scheduler.shutdown();
}
}
}
에러 발생
- 위 소스를 실행하면 아래와 같은 에러가 발생합니다.
- 원인 : oracle JDBC 드라이버 (ojdbc*. jar 파일)가 포함되지 않아 발생합니다.
No suitable driver found for jdbc
- java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@127.0.0.1:1521:orcl
- 아래와 같이 ojdbc.jar 파일을 다운로드하여 추가해 주면 에러가 조치됩니다.
- 아래 글 참고 하시면 됩니다.
2025.04.29 - [분류 전체 보기] - java 애플리케이션 logger #004
java 애플리케이션 logger #004
java 배포 logger배포 시스템에 log를 남겨 보겠습니다. Maven, Gradle 이 아니므로 jar 파일을 직접 추가합니다. 메뉴 구조추가된 파일만 표시했습니다. 파일 > 프로젝트 구조... 프로젝트 구조 > 모듈 >
st-d.tistory.com
반응형