JDBC 위한 Basic Method 만들기

  • JDBC를 위해 매번 새로 해야 하는 작업을 메서드로 만들어 후에는 생성만으로 실행
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
  • import 받은 클래스
public class DBConnect {
	
	//url	
	static final String ORACLE_URL="jdbc:oracle:thin:@localhost:1521:XE";
	
	//driver
	String driver="oracle.jdbc.driver.OracleDriver";

	public DBConnect() {
		try {
			Class.forName(driver);
			System.out.println("오라클 드라이버 성공!!!");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("오라클 드라이버 실패!!!");
		}
	}
  • url은 현재 localhost로 지정
  • driver 실행을 위한 명령(Oracle에서는 driver 생략 가능)
  • driver는 configure build path를 통해 외부 jar를 설치해야 함)
//Connection
	public Connection getConnection() {
		
		Connection conn=null;
		
		try {
			conn=DriverManager.getConnection(ORACLE_URL, "RheeMingyu", "a1234");

		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("오라클 연결실패: url,계정,비번확인요함!!!"+e.getMessage());
		}
		
		return conn;
	}
  • Connection은 Oracle과 Java를 연결하는 작업
  • 미리 Connection을 실행하는 메서드 작성(여기서 Connection에 대한 try~catch 이미 실행)
//close메서드...총 4개
	public void dbClose(ResultSet rs,Statement stmt,Connection conn) {
		
		try {
			if(rs!=null) rs.close();
			if(stmt!=null) stmt.close();
			if(conn!=null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void dbClose(Statement stmt,Connection conn) {
		
		try {
			if(stmt!=null) stmt.close();
			if(conn!=null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void dbClose(ResultSet rs,PreparedStatement pstmt,Connection conn) {
		
		try {
			if(rs!=null) rs.close();
			if(pstmt!=null) pstmt.close();
			if(conn!=null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void dbClose(PreparedStatement pstmt,Connection conn) {
		
		try {
			if(pstmt!=null) pstmt.close();
			if(conn!=null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
  • Connection, Statement, ResulSet을 매개변수로 받음
  • select를 위해 ResultSet(rs)이 있는 메서드, 없는 메서드
  • 미완성 SQL문을 받기 위한 PreparedStatement가 있는 메서드, 없는 메서드

CRUD를 위한 Method

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
  • import 받은 클래스
public class CRUDTest {

	DBConnect db=new DBConnect();
  • JDBC를 위한 기본 메서드를 사용하기 위해 클래스(DBConnect) 생성

INSERT

public void insert() {
		
		Scanner sc=new Scanner(System.in);
			
		System.out.println("이름입력");
		String name=sc.nextLine();
		
		System.out.println("주소입력");
		String addr=sc.nextLine();
		
		String sql="insert into myinfo values (seq1.nextval,'"+name+"','"+addr+"',sysdate)";
		
		//1.db연결
		Connection conn=db.getConnection(); //이미 기본 메서드에서 try~catch 처리
		//2.statement
		Statement stmt=null;
		
		try {
			stmt=conn.createStatement();
			stmt.execute(sql);
			
			System.out.println("***정보가 추가되었습니다***");
			
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("insert error: "+e.getMessage());
		} finally {
			db.dbClose(stmt, conn);
		}
	}
  • Scanner를 통해 필요한 정보를 입력 받고 이를 변수화하여 SQL문에 삽입
  • ResultSet 객체를 생성하지 않았으므로 stmt의 execute 메서드를 이용하여 SQL문 입력

SELECT

public void select() {
		
		//Connection
		Connection conn=db.getConnection();
		Statement stmt=null;
		ResultSet rs=null;
		
		String sql="select * from myinfo order by num";
		
		System.out.println("시퀀스\t이름\t주소\t입력시간");
		
		try {
			stmt=conn.createStatement();
			rs=stmt.executeQuery(sql);
			
			//2개이상일경우는 while문
			//resultset객체의 next이용해서 행을선택, get메서드를 이용해서 테이블의 컬럼값을 획득
			while(rs.next())
			{
				int num=rs.getInt("num");
				String name=rs.getString("name");
				String addr=rs.getString("addr");
				String sdate=rs.getString("sdate");
				
				System.out.println(num+"\t"+name+"\t"+addr+"\t"+sdate);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("select error"+e.getMessage());
		} finally {
			db.dbClose(rs, stmt, conn);
		}
	}
  • ResultSet 객체의 next이용해서 행을 선택, get메서드를 이용해서 테이블의 컬럼 값을 획득

DELETE

public void delete() {
		Scanner sc=new Scanner(System.in);
		
		System.out.println("삭제할 시퀀스 입력");
		int n=Integer.parseInt(sc.nextLine());
		
		String sql="delete from myinfo where num="+n;
		
		//db연결
		Connection conn=db.getConnection();
		//statement
		Statement stmt=null; //try~catch문에 갇히지 않게 하기 위해서
		
		try {
			stmt=conn.createStatement();
			
			//sql문 실행
			int a=stmt.executeUpdate(sql); //성공한 갯수
			
			if(a==0) //없는번호 입력시 실제 삭제가 되지않으므로 0반환
				System.out.println("없는 데이터 번호입니다");
			else //삭제되면 1반환
				System.out.println("***정보가 삭제되었습니다***");
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.dbClose(stmt, conn);
		}
	}
  • SQL문을 실행할 시 stmt의 executeUpdate 메서드를 사용하면 실행에 성공한 개수(0 or 1)를 반환
  • 없는 번호 입력 시 executeUpdate 메서드가 실행되지 않으므로 0 반환

UPDATE

public void update() {
		
		//수정할 시퀀스 입력후 이름,주소 입력
		Scanner sc=new Scanner(System.in);
		System.out.println("수정할 시퀀스는?");
		String n=sc.nextLine();
		
		//위의 boolean메서드 가져와서 실행
		/*if(!this.isData(n))
		{
			System.out.println("해당번호는 존재하지 않습니다");
			return; //메서드 종료
		}*/
		
		System.out.println("수정할 이름은?");
		String name=sc.nextLine();
		
		System.out.println("수정할 주소는?");
		String addr=sc.nextLine();
		
		//sql
		String sql="update myinfo set name='"+name+"',addr='"+addr+"' where num="+n;
		
		System.out.println(sql);
		
		Connection conn=db.getConnection();
		Statement stmt=null;
		
		try {
			stmt=conn.createStatement();
			
			int a=stmt.executeUpdate(sql);
			
			if(a==0)
				System.out.println("수정할 데이터가 존재하지 않습니다");
			else
				System.out.println("***수정되었습니다***");
			
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("update error: "+e.getMessage());
		} finally {
			db.dbClose(stmt, conn);
		}
	}
  • 없는 시퀀스를 입력할 시에도 수정할 데이터 값을 입력하게 됨
  • 위의 값들을 입력 후에 수정할 데이터 존재 유무를 확인하게 되어 낭비 발생
  • 이를 처리하기 위해 아래의 메서드 추가적으로 작성(/* */에 포함된 코드 활성화)
  • return은 메서드 자체를 종료하기 위한 명령어
//update할때 없는번호인지 있는번호인지 찾아주기
	public boolean isData(String n) {
		
		//n에 해당하는 데이터가 있으면 true,없으면 false
		boolean flag=false;
		
		String sql="select * from myinfo where num="+n;
		
		Connection conn=db.getConnection();
		Statement stmt=null;
		ResultSet rs=null;
		
		try {
			stmt=conn.createStatement();
			rs=stmt.executeQuery(sql);
			
			//1개일경우는 if문
			if(rs.next()) //데이터가 있는경우
				flag=true;
			else //없는경우
				flag=false;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.dbClose(rs, stmt, conn);
		}
		
		return flag;
	}
  • 조회문(select)를 이용하여 해당 시퀀스의 행이 존재하는지 확인
  • 이를 통해 boolean 값(flag)을 변경
  • 결과로써 return된 boolean 값을 위의 update 메서드의 적절한 위치(시퀀스 입력 직후)에서 실행
  • SEARCH는 다른 위의 코드들과 다른 클래스에서 작성
  • preparedstatement(pstmt) 사용
public void searchSangpum() {
		System.out.println("검색할 상품명(일부)");
		String sang=sc.nextLine();
		
		String sql="select * from myshop where sangpum like ?";
		
		System.out.println("시퀀스\t상품명\t수량\t가격\t입고일자");
		
		Connection conn=db.getConnection();
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		
		try {
			pstmt=conn.prepareStatement(sql);
			
			pstmt.setString(1, "%"+sang+"%");
			
			rs=pstmt.executeQuery();
			
			while(rs.next())
			{
				int shopnum=rs.getInt("shopnum");
				String sangpum=rs.getString("sangpum");
				int su=rs.getInt("su");
				int price=rs.getInt("price");
				String ipgo=rs.getString("ipgo");
				
				System.out.println(shopnum+"\t"+sangpum+"\t"+su+"\t"+price+"\t"+ipgo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.dbClose(rs, pstmt, conn);
		}
	}
  • 검색(search)은 출력(select)을 해야하므로 ResultSet 사용
  • 일부 검색 기능을 위해 SQL문에 like ‘%’ 사용
  • ‘%’를 pstmt.setString( )에서 입력하기 위해서는 “%”+(변수)+”%”와 같이 입력

실행 & 출력

public static void main(String[] args) {

		CRUDTest crud=new CRUDTest();
		
		Scanner sc=new Scanner(System.in);
		int n;
		
		while(true)
		{
			System.out.println("***Oracle db 연습_myinfo***");
			System.out.println("1.insert 2.select 3.delete 4.update 9.종료");
			
			n=Integer.parseInt(sc.nextLine());
			
			if(n==1)
				crud.insert();
			else if(n==2)
				crud.select();
			else if(n==3)
				crud.delete();
			else if(n==4)
				crud.update();
			else if(n==9)
			{
				System.out.println("종료합니다");
				break;
			}
		}
	}
}
profile
초보개발자

0개의 댓글