티스토리 뷰

Programming/JDBC

[JDBC] Insert 문 실행

Allg 2017. 6. 27. 12:43


Insert 문 실행

1. JDBC 드라이버를 로딩

  • Class.forName(“com.mysql.jdbc.Driver”)

2. Connection 객체를 생성

  • con = DriverManager.getConnection(url, user, pw)

3. PreparedStatement 객체 생성, 객체 생성시 SQL 문장 저장

  • PreparedStaement - SQL문을 데이터베이스에 보내기위한 객체입니다.
  • pstmt = con.preparedStatement(“SQL 문장”)

4. pstmt.set<데이터타입>(? 순서, 값)

  • ? 매개변수에 값을 지정합니다.
  • ex) pstmt.setString(1, 값), pstmt.setInt(2, 값)

5. SQL 문장을 실행하고 결과를 리턴

  • SQL 문장 실행 후, 변경된 row 수를 int type 으로 리턴합니다.
  • 변경된 row 수가 0 이면 삭제된 행이 없습니다.
  • pstmt.excuteUpdate()
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Insert {

    public static void main(String[] args) {

        Connection con = null;                                     // 데이터 베이스와 연결을 위한 객체
        PreparedStatement pstmt = null;                            // SQL 문을 데이터베이스에 보내기위한 객체

        // 1. JDBC Driver Class - com.mysql.jdbc.Driver
        String driver = "com.mysql.jdbc.Driver";

        // 2. 데이터베이스에 연결하기 위한 정보
        String url = "jdbc:mysql://localhost:3306/test_db";       // 연결문자열
        String user = "root";                                     // 데이터베이스 ID
        String pw = "admin1214";                                  // 데이터베이스 PW

        String SQL = "insert into customers(id, pass, name, phone, email) values(?, ?, ?, ?, ?)";

        try {
            // 1. JDBC 드라이버 로딩 - MySQL JDBC 드라이버의 Driver Class 로딩
            Class.forName(driver);

            // 2. Connection 생성 - .getConnection(연결문자열, DB-ID, DB-PW)
            con = DriverManager.getConnection(url, user, pw);

            // 3. PreParedStatement 객체 생성, 객체 생성시 SQL 문장 저장
            pstmt = con.prepareStatement(SQL);

            // 4. pstmt.set<데이터타입>(? 순서, 값) ex).setString(), .setInt ...
            pstmt.setString(1, "grasshopper");
            pstmt.setString(2, "5123");
            pstmt.setString(3, "유재석");
            pstmt.setString(4, "010-4921-1354");
            pstmt.setString(5, "allg@gmail.com");

            // 5. SQL 문장을 실행하고 결과를 리턴 - SQL 문장 실행 후, 변경된 row 수 int type 리턴
            int r = pstmt.executeUpdate();

            // pstmt.excuteQuery() : select
            // pstmt.excuteUpdate() : insert, update, delete ..

            System.out.println("변경된 row : " + r);

        } catch (SQLException e) {

            System.out.println("[SQL Error : " + e.getMessage() + "]");

        } catch (ClassNotFoundException e1) {

            System.out.println("[JDBC Connector Driver 오류 : " + e1.getMessage() + "]");

        } finally {

            //사용순서와 반대로 close 함
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


'Programming > JDBC' 카테고리의 다른 글

[JDBC] DAO  (2) 2017.07.03
[JDBC] Delete 문 실행  (0) 2017.06.30
[JDBC] Update 문 실행  (2) 2017.06.30
[JDBC] Select 문 실행  (6) 2017.06.26
[JDBC] JDBC 드라이버 로딩과 Connection 생성  (3) 2017.06.26
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함