Framework & Library/JDBC

[JDBC] INSERT문/UPDATE문/DELETE문 요청

gangintheremark 2023. 8. 1. 17:18
728x90
 

[JDBC] JDBC 실행 순서 정리 ✍️ - SELECT문 요청

JDBC(Java Database Connectivity) 는 어떤 환경에서건 자바 언어를 사용하는 경우에 DBMS 종류에 상관없이 데이터베이스에 접근할 수 있는 독립적인 프로그래밍 API이다. 다음은 JDBC를 구현하는 기본적인

gangintheremark.tistory.com

레코드 추가하기 - INSERT

다음은 dept 테이블에 새로운 레코드를 저장하는 자바 프로그램이다.

요청할 SQL문을 작성할 때, 저장할 데이터 대신에 ? 기호를 사용한다. 나중에 set메서드를 사용하여 값을 동적으로 설정한다. 데이터타입에 따라 setInt(순서, 값) , setString(순서, 값)을 사용한다.( 여기서 순서는?기호의 순서)

import java.sql.*;

public class InsertTest {

        public static void main(String[] args) throws SQLException {
            String driver = "oracle.jdbc.driver.OracleDriver";
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            String userid = "SCOTT";
            String passwd = "TIGER";

            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            Connection con = null;
            PreparedStatement pstmt = null;

            try {
                con = DriverManager.getConnection(url, userid, passwd);
                String sql = "insert into dept (deptno, dname,loc) "  
                            + " values (?, ?, ?)";
                pstmt = con.prepareStatement(sql);

                pstmt.setInt(1, 50);
                pstmt.setString(2, "개발");
                pstmt.setString(3, "서울");

                int num = pstmt.executeUpdate();
                System.out.println("레코드 생성갯수 : " + num);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (pstmt != null)
                        pstmt.close();
                    if (con != null)
                        con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
}


레코드 수정하기 - UPDATE

다음은 dept 테이블에 저장된 레코드를 수정하는 자바 프로그램이다.

import java.sql.*;

public class UpdateTest {

        public static void main(String[] args) throws SQLException {
            String driver = "oracle.jdbc.driver.OracleDriver";
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            String userid = "SCOTT";
            String passwd = "TIGER";

            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            Connection con = null;
            PreparedStatement pstmt = null;

            try {
                con = DriverManager.getConnection(url, userid, passwd);
                String sql = "update dept set dname=?, loc=? where deptno=?";
                pstmt = con.prepareStatement(sql);

                pstmt.setInt(3, 50);
                pstmt.setString(1, "인사");
                pstmt.setString(2, "경기");

                int num = pstmt.executeUpdate();
                System.out.println("레코드 수정갯수 : " + num);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (pstmt != null)
                        pstmt.close();
                    if (con != null)
                        con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
}


레코드 삭제하기 - DELETE

다음은 dept 테이블에 저장된 레코드를 삭제하는 자바 프로그램이다.

import java.sql.*;

public class DeleteTest {

        public static void main(String[] args) throws SQLException {
            String driver = "oracle.jdbc.driver.OracleDriver";
            String url = "jdbc:oracle:thin:@localhost:1521:xe";
            String userid = "SCOTT";
            String passwd = "TIGER";

            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            Connection con = null;
            PreparedStatement pstmt = null;

            try {
                con = DriverManager.getConnection(url, userid, passwd);
                String sql = "delete from dept where deptno=?";
                pstmt = con.prepareStatement(sql);

                pstmt.setInt(1, 50);

                int num = pstmt.executeUpdate();
                System.out.println("레코드 제거갯수 : " + num);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (pstmt != null)
                        pstmt.close();
                    if (con != null)
                        con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
}


 

parameter index out of range (1 > number of parameters, which is 0) 해결

board 테이블에서 제목에 subject를 포함하고 있는 글 정보 return하는 함수를 구현하던 중
parameter index out of range (1 > number of parameters, which is 0). 에러를 마주했다.

 

? 기호를 잘못 사용할 때 발생하는 에러로 다음과 같이 sql을 작성하니 발생했다.

String sql = "select * from board where subject like '%?%'";

에러를 해결하려면 다음과 같이 sql을 작성하면 된다.

String sql = "select * from board where subject like '%' ||  ?  || '%'";
728x90