중복코딩방지를 위해
오라클 연결 과정 과 SQL문 실행들을 메소드로 빼서
필요할 때 메소드 호출로 불러 올 것!
인터페이스
// 메소드로 상속할 인터페이스 생성(오라클 연결,sql실행문,객체닫기,사용자에게 값 받기)
public interface IConnect {
// 멤버상수에 데이터로딩, 데이터베이스연결
String ORACLE_DRIVER = "oracle.jdbc.OracleDriver";
String ORACLE_URL = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
//추상메소드 데이터베이스연결(sqlplus로그인),쿼리문전송,닫기,사용자값받기,쿼리문입력(>SQL)
void connect(String url,String user,String password);
void execute() throws Exception;
void close();
String getValue(String message);
String getQueryString();
}
메소드 호출 할 부모 클래스 생성
public class IConnectImpl implements IConnect{
//멤버변수
public Connection conn;
public ResultSet rs;
public Statement stmt;
public PreparedStatement psmt;
public CallableStatement csmt;
private Scanner sc = new Scanner(System.in);
//static 블락 여기다가 맨 처음 드라이버 로딩할 거
static {
try{ //데이터로딩
Class.forName(ORACLE_DRIVER);
}
catch(ClassNotFoundException e){
System.out.println("드라이버 로딩 실패:"+e.getmessage);
}
}
//기본생성자
public IConnectImpl(){}
//인자생성자 --이거로 데이터베이스 연결해서 로그인해도 되고(여기서 바로 인자 넣거나 메인에서 넣거나)
public IConnectImpl(String url, String user, String password) {
connect(url, user, password);
}
@Override
public void connect(String url, String user, String password) {
try { // 이걸로 데이터베이스 연결해서 로그인해도 된다!
conn = DriverManager.getConnection(url, user, password);
}
catch (SQLException e) {
System.out.println("데이터베이스 연결 실패:"+e.getMessage());
}
}
@Override //부모로 사용할거라서 구현은 안해도 됨! 자식에서 구현해도 됩니다
public void execute() throws Exception { }
@Override // 연결끊기 메소드
public void close() {
try {
if (csmt != null) csmt.close();
if (psmt != null) psmt.close();
if (stmt != null) stmt.close();
if (rs != null) rs.close();
if (conn != null) conn.close();
}
catch(SQLException e){}
}
@Override //사용자용 입력 메소드
public String getValue(String message) {
System.out.println(message + "를 입력하세요");
String value = sc.nextLine();
if("exit".equalsIgnoreCase(value)) {
close();
System.out.println("프로그램 종료");
System.exit(0);
}
return value;
}
@Override
public String getQueryString() {
return null;
}
}
'학원 > JDBC' 카테고리의 다른 글
10/24 27-4 (insertSQLAutoGeneratedKeys) (0) | 2022.10.24 |
---|---|
10/24 27-3 (UpdateSQL.statement) (0) | 2022.10.24 |
10/24 27-1( DeleteSQL.statement ) (0) | 2022.10.24 |
10/21 26-7( InsertSQL .statement ) (0) | 2022.10.23 |
10/21 26-6 DBconnection(실전이닷) (0) | 2022.10.23 |