기초JAVA 23강 - JDBC

Whatever·2021년 10월 12일
0

기초 JAVA

목록 보기
23/26

Java Database Connectivity

  • 자바와 데이터베이스를 연결해주는 라이브러리
  • ojdbc : 오라클 JDBC

JDBC 작성단계

  1. Connection 생성 - Oracle과 Java를 연결
  2. Statement 생성 - 쿼리를 Statement객체로 생성
  3. Query 실행 -> 실행결과가 Java로 넘어옴
  4. ResultSet에서 결과 추출(Select인 경우) - Insert, Update, Delete인 경우는 결과 없음
  5. ResultSet, Statement, Connection 닫기
//데이터베이스 접속 정보
        String url = "jdbc:oracle:thin:@localhost:1521:xe"; 
        //@기준으로 앞부분 : 오라클에 접속하기위한 드라이버 정보(드라이버 이름)
        String user = "JYJ94";
        String password = "java";	

	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	//try-catch로 감쌀거라서 변수를 먼저 만든 것.
	//연결할 때는 DriverManager라는 클래스가 필요
	
	try {
		con = DriverManager.getConnection(url, user, password);
                //DriverManager : Driver를 관리해주는 클래스, connection이라는 객체를 리턴
		//쿼리 작성 - 오라클에서 만들었던 SQL문을 String 타입으로 만들어서 저장
		String sql = "Select * from member";
		ps = con.prepareStatement(sql); //SQL문은 Statement 객체로 변환해서 저장해야함.
		
		//실행할 때 두 종류의 메서드 있음 - 둘의 차이는 리턴타입 쿼리 실행 후 리턴해주는 결과가 다름
		//select - resultSet을 리턴
		rs = ps.executeQuery();//조회 결과가 resultSet의 형태로 담겨서 오는 것
		
		//insert, update, delete - int를 리턴
		//int result = ps.executeUpdate();//영향받은 행의 개수를 리턴해줌 
              - 지금 SQL문은 select이기 때문에 주석처리
		
		while(rs.next()) {//resultSet의 next()메서드 
               : 첫번째 행을 바라보게 됨, 첫번째 행에서 값을 추출할 수 있음.
			//while문이 반복되면서 next가 호출될 수록 한 줄씩 내려가면서 행을 바라봄
			//다음 행이 있는지 없는지 알아보면서 다음행을 바라봄, 
                        -> 다음행이 있다 : true, 없다 : false
			String memId = rs.getString(1);
            //값을 하나씩 가져올 때 get메서드를 사용, 
            //String타입의 메서드를 가져온다는 뜻. 1의 뜻 : 첫번째 컬럼
			String memPass = rs.getString("MEM_PASS");
            //컬럼명, getString(컬럼의 순서나 컬럼의 이름);을 넣어주면 됨.
			
			System.out.println("MEM_ID : " + memId + "/ MEM_PASS : " + memPass);
            //조회까지 해 줌.
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}finally {//호출해서 닫아주기
		if(rs != null) try { rs.close(); } catch(Exception e) {}
        //호출하려면 try-catch로 묶어줘야함.
		if(ps != null) try { ps.close(); } catch(Exception e) {}
		if(con != null) try { con.close(); } catch(Exception e) {}
	}
    

SELECT 문

public class Select {

    public static void main(String[] args) {
//		1. Connection 생성 - Oracle과 Java를 연결
//		2. Statement 생성 - 쿼리를 Statement객체로 생성
//		3. Query 실행 ->  실행결과가 Java로 넘어옴
//		4. ResultSet에서 결과 추출(Select인 경우) - Insert, Update, Delete인 경우는 결과 없음
//		5. ResultSet, Statement, Connection 닫기

	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	String user = "JYJ94";
	String password = "java";
	
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	
	try {
		con = DriverManager.getConnection(url, user, password);
		
		String sql = "select * from lprod where lprod_gu = ?";
		ps = con.prepareStatement(sql);
		ps.setString(1, "P403");
		
		rs = ps.executeQuery();
		
		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();
		
		while(rs.next()) {
			
			for(int i = 1; i <= columnCount; i++) {
				Object value = rs.getObject(i);
				System.out.print(value + "\t");
			}
			System.out.println(); 
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}finally {
		if (rs != null) try {rs.close();} catch(Exception e) {}
		if (ps != null) try {ps.close();} catch(Exception e) {}
		if (con != null) try {con.close();} catch(Exception e) {}
	}
	
}

}

UPDATE문

public class Update {

public static void main(String[] args) {
	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	String user = "JYJ94";
	String password = "java";
	
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	
	try {
		con = DriverManager.getConnection(url, user, password);
		
		String sql = "update lprod set lprod_nm = ? where lprod_gu = ?";
		ps = con.prepareStatement(sql);
		ps.setString(1, "도서");
		ps.setString(2, "P402");
		
		int result = ps.executeUpdate();
		System.out.println(result);
		
	} catch (SQLException e) {
		e.printStackTrace();
	}finally {
		if(ps != null) try{ ps. close(); } catch(Exception e) {}
		if(con != null) try{ con. close(); } catch(Exception e) {}
	}
}

} 
    
    

INSERT문

public class Insert {

public static void main(String[] args) {
	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	String user = "JYJ94";
	String password = "java";
	
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	
	try {
		con = DriverManager.getConnection(url, user, password);
		
		String sql = "insert into lprod values (?, ?, ?) ";
		
		ps = con.prepareStatement(sql);
		ps.setInt(1, 10);
		ps.setString(2, "P501");
		ps.setString(3, "기타 잡화");
		
		int result = ps.executeUpdate();
		System.out.println(result);
		
	} catch (SQLException e) {
		e.printStackTrace();
	}finally {
		if(rs != null)try { rs.close(); }catch(Exception e) {}
		if(ps != null)try { ps.close(); }catch(Exception e) {}
		if(con != null)try { con.close(); }catch(Exception e) {}
	}
}

}

DELETE문

public class Delete {

public static void main(String[] args) {
	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	String user = "JYJ94";
	String password = "java";
	
	Connection con = null;
	PreparedStatement ps = null;
	int result = 0;
	
	try {
		con = DriverManager.getConnection(url, user, password);
		
		String sql = "delete from lprod where lprod_gu = ?";
		ps = con.prepareStatement(sql);
		ps.setString(1, "P501");
		
		result = ps.executeUpdate();
		System.out.println(result);
		
	} catch (SQLException e) {
		e.printStackTrace();
	}finally {
		if(ps != null)try {ps.close();}catch(Exception e) {}
		if(con != null)try {con.close();}catch(Exception e) {}
	}
}

}

    

0개의 댓글

관련 채용 정보