ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 14. JDBCConnectTest
    개발자 수업/DB 2021. 11. 16. 17:57

    1. 데이터베이스 연동 프로그래밍 환경
        1) DB
        2) DB와 JAva App을 연결하는 드라이버 : ojdbc8.jar

    2. 데이터베이스 접속 자바 클래스
        1) java.lang.Class          forName("클래스이름");
                                    -> JDBC 드라이버 로딩
        2) java.sql.DriverManager   getConnection(url, user, password);
                                    -> DB Connection 객체 생성
                    Connection      createStatement()
                                    -> SQL문 실행하는 Statement 객체를 생성
                    Statement       executeQuery(sql);
                                    -> SQL문 실행해서 ResultSet 객체를 생성
                                    executeUpdate(sql);
                    ResultSet       getString(), getInt() ...
                                    -> 쿼리 실행결과를 반환

     

    package kr.co.ezenac;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JdbcConnTest {
    	
    	Connection conn;
    	
    	public JdbcConnTest() {
    		String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
    		String userid = "wdsql";
    		String pwd = "0311";
    		
    		try {
    			//드라이버 찾는 부분
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    			System.out.println("드라이버 로드 성공");
    			
    			System.out.println("데이터베이스 연결 준비");
    			conn = DriverManager.getConnection(url, userid, pwd);
    			System.out.println("데이터베이스 연결 성공");
    			
    		} catch (Exception e) {
    			//e.printStackTrace();
    			System.out.println(e.getMessage());
    		}
    		
    	}
    	
    	public void sqlExecute() throws SQLException {
    		
    		String query = "select * from Book";		//SQL문
    		
    		try {
    			Statement stmt = conn.createStatement();
    			ResultSet rs = stmt.executeQuery(query);
    			
    			System.out.println("BOOKID \t BOOKNAME \t\t PUBLISHER \t PRICE");
    			while(rs.next()) {
    				System.out.print(rs.getInt(1));
    				System.out.print("\t" + rs.getString(2));
    				System.out.print("\t\t" + rs.getString(3));
    				System.out.print("\t" + rs.getInt(4));
    				System.out.println();
    			}
    			
    		} catch (SQLException e) {
    			//e.printStackTrace();
    			System.out.println(e.getMessage());
    		} finally {
    			conn.close();
    		}
    	}
    	
    	public static void main(String[] args) throws SQLException {
    		JdbcConnTest jConnTest = new JdbcConnTest();
    		jConnTest.sqlExecute();
    	}
    }

    '개발자 수업 > DB' 카테고리의 다른 글

    16. 데이터베이스 설계  (0) 2021.11.16
    15. SELECT  (0) 2021.11.16
    13. CASE  (0) 2021.11.16
    12. 서브쿼리  (0) 2021.11.12
    11. 조인  (0) 2021.11.12

    댓글