DB/Oracle

InsertBatch

swhwang 2016. 5. 4. 23:39

// Filename : InsertBatch.java

import java.sql.*;

import java.util.*;

public class InsertBatch {

  public static void main(String args[]) {

try {

      Statement stmt;

      ResultSet rs;


// JDBC 드라이버를 로드한다.

Class.forName("oracle.jdbc.driver.OracleDriver");

// 데이터베이스에 접속한다. 적절한 JDBC URL 설정한다.          

      Connection con = 

    DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL", "javatest", "javatest");

              

        stmt = con.createStatement();

//ResultSet.TYPE_SCROLL_SENSITIVE,

//        ResultSet.CONCUR_UPDATABLE);


rs = stmt.executeQuery("SELECT num, name FROM student");

      while( rs.next() ) {

System.out.print(rs.getInt(1));

System.out.println(rs.getString(2));

      }

      stmt.addBatch(OraCon.toDB("INSERT INTO student VALUES " + 

"(6, '김나나', '서울 송파구', 85.6)"));

stmt.addBatch(OraCon.toDB("INSERT INTO student VALUES " + 

"(7, '허 준', '서울 동대문구', 77.5)"));

stmt.addBatch(OraCon.toDB("INSERT INTO student VALUES " + 

"(8, '이정수', '서울 동작구', 88)"));

     

      System.out.println("====== 배치 명령 수행  =======");

      int[] updateCounts = stmt.executeBatch(); 

      rs = stmt.executeQuery("SELECT num, name FROM student");

  while( rs.next() ) {

System.out.print(rs.getInt(1));

System.out.println(OraCon.fromDB(rs.getString(2)));

      }

}

catch( Exception e ) {

  if (e instanceof BatchUpdateException) {

              BatchUpdateException b = (BatchUpdateException)e;

System.err.println("SQLException: " + b.getMessage());

System.err.println("SQLState:  " + b.getSQLState());

System.err.println("Message:  " + b.getMessage());

System.err.println("Vendor:  " + b.getErrorCode());

System.err.print("Update counts:  ");

int [] updateCounts = b.getUpdateCounts();

for (int i = 0; i < updateCounts.length; i++) {

System.err.print(updateCounts[i] + "   ");

}

  } else {

    e.printStackTrace();

  }

}

    }

}