Database/DBMS

[DBMS] JDBC에서 Query 사용

오류나면꽥꽥 2024. 2. 15. 09:59
executeQuery()   SQL Query문이 SELECT의 경우 사용
  반환값 타입 ResultSet
executeUpdate()    SQL Query문이 INSERT, DELETE, UPDATE의 경우 사용
   반환값 타입 int

 

 

 

 

 

✋ 알아두기

  • JDBC 동작 순서
  1. 변수 세팅(Connection, Statement, ResultSet)
  2. JDBC Driver 등록
  3. Connection 객체 생성
  4. Statement 객체 생성
  5. 실행할 Query
  6. ResultSet 객체로부터 데이터 조회
  7. ResultSet 객체 close
  8. Statement 객체 close
  9. Connection 객체 close

 

 

 

✅ executeQuery()

ex)

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectTest {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try{
            // 1. 드라이버 로딩
            Class.forName("com.mysql.jdbc.Driver");

            // 2. DB연결하기
            String url = "jdbc:mysql://localhost/dev";
            String userName="root";
            String passwd="1234";
            conn = DriverManager.getConnection(url, userName, passwd);

            // 3. 쿼리 수행을 위한 Statement 객체 생성
            stmt = conn.createStatement();

            // 4. SQL 쿼리 작성
            String sql = "SELECT name, owner, date_format(birth, '%Y년%m월%d일' date FROM pet";


            // 5. 쿼리 수행
            // 레코드들은 ResultSet 객체에 추가된다.
            rs = stmt.executeQuery(sql);

            // 6. 실행결과 출력하기
            while(rs.next()){
                String name = rs.getString(1);
                String owner = rs.getString(2);
                String date = rs.getString(3);

                System.out.println(name + " " + owner + " " + date);
            }
        }
        catch( ClassNotFoundException e){
            System.out.println("드라이버 로딩 실패");
        }
        catch( SQLException e){
            System.out.println("에러 " + e);
        }
        finally{
            try{
                if( conn != null && !conn.isClosed()){
                    conn.close();
                }
                if( stmt != null && !stmt.isClosed()){
                    stmt.close();
                }
                if( rs != null && !rs.isClosed()){
                    rs.close();
                }
            }
            catch( SQLException e){
                e.printStackTrace();
            }
        }
    }
}

 

 

 

 

 

executeUpdate()

ex)

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectTest {
    public Object[] TestInfo(String id) throws SQLException, Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer str = new StringBuffer();

        try{
            // 1. 드라이버 로딩
            Class.forName("com.mysql.jdbc.Driver");

            // 2. DB연결하기
            String url = "jdbc:mysql://localhost/dev";
            String userName="root";
            String passwd="1234";
            conn = DriverManager.getConnection(url, userName, passwd);

            // 3. 쿼리 수행을 위한 Statement 객체 생성
            stmt = conn.createStatement();

            try{
            	str.setLength(0);
                str.append("delete userInfo where userId=?");
                
                pstmt.setString(1, id);
                rs = pstmt.executeUpdate();
            }
        }
        catch( ClassNotFoundException e){
            System.out.println("드라이버 로딩 실패");
        }
        catch( SQLException e){
            System.out.println("에러 " + e);
        }
        finally{
            try{
                if( conn != null && !conn.isClosed()){
                    conn.close();
                }
                if( stmt != null && !stmt.isClosed()){
                    stmt.close();
                }
                if( rs != null && !rs.isClosed()){
                    rs.close();
                }
            }
            catch( SQLException e){
                e.printStackTrace();
            }
        }
    }
}

'Database > DBMS' 카테고리의 다른 글

[DBMS] 서브 쿼리  (0) 2024.02.16
[DBMS] JDBC 연결방법  (0) 2024.02.15
[DBMS] JDBC  (0) 2024.02.14