본문 바로가기

Java

JDBC: DB(mySQL+aws)의 데이터 수정

import java.sql.*;
 
public class InsertInto {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement stmt = null;
 
        int id = 6;
        String title = "no sequence";
        String writer_id = "tiletocode";
        String content = "plz get nextval()";
        String files = "";
 
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //jdbc:mysql://aws 엔드포인트 주소/스키마명
            String url = "jdbc:mysql://ledx-1.c0puka4oucjv.ap-northeast-2.rds.amazonaws.com/tiletocode";
            conn = DriverManager.getConnection(url, "tiletocode""****");
            //DB계정, 비밀번호 기입
            System.out.println("DB서버 연결 성공.");
 
            //쿼리문
            String sql = "INSERT INTO NOTICE(id, title, writer_id, content)" +
                                    " values(?,?,?,?)";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, id);
            stmt.setString(2, title);
            stmt.setString(3, writer_id);
            stmt.setString(4, content);
 
            int result = stmt.executeUpdate();
            System.out.println(result + "개의 값이 추가되었습니다.");
 
            stmt.close();
            conn.close();
            //인스턴스를 닫을땐 선언의 역순으로
        }
        catch(ClassNotFoundException e) {
            System.out.println("드라이버 로딩 실패");
        }
        catch (SQLException e) {
            System.out.println("에러: " + e);
        }
        finally {
            try {
                if(conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
cs

 

기본골격은 SELECT 쿼리문을 작성할때와 같다.

 

Checklist

 - 결과값을 얻을 목적이 아니므로 ResultSet 클래스 참조는 제외한다.

   마찬가지로executeQuery메소드 대신 executeUpdate메소드를 쓴다.

 - 쿼리문에 INSERT할 데이터를 직접 기입하기보다

   쿼리문에서는 ?로 처리하고 PreparedStatement클래스의 set메소드를 사용하면 코드가 깔끔해진다.

   이때 column index는 배열과 달리 1부터 시작한다.

 

 

INSERT 실행전
실행후

만약 컬럼에 기본값이 설정되어 있지 않으면 쿼리문에서 반드시 값을 추가해줘야 오류가 나지 않는다

(예시에서 REGDATE 컬럼에는 기본값으로 CURRENT_TIMESTAMP가 설정되어 있음)

 

 

 - 보완해야할것

mySQL에선 시퀀스가 별도로 존재하지 않아 ID값을 반드시 확인해야하는데

mySQL에서도 시퀀스를 구현할수 있으니 그 방법으로 JDBC에도 ID값을 따로 입력받을 필요없이

자동으로 추가할수 있게 고칠것