2014-03-03 2 views
1

JDBC를 사용하여 데이터베이스를 호출하는 일괄 처리 프로그램이 있습니다. 'ID'를 기본 키로하여 일괄 100으로 정보를 전송합니다.Java를 사용하여 여러 SQL 문을 실행하는 방법은 무엇입니까?

데이터베이스를 한 번 호출 한 다음 연결을 닫기 전에 여러 SQL 문을 실행하려고합니다.

나는 참조

내가 루프의 각 ID를 한 번에 세 가지 일을 할
 // Database credentials 
     String USER = username; 
     String PASS = password; 

     Connection connec = null; 
     Statement stmt = null; 

     //STEP 2: Register JDBC driver 
     Class.forName("com.mysql.jdbc.Driver"); 

     //STEP 3: Open a connection 
     System.out.println("Connecting to a selected database..."); 
     connec = DriverManager.getConnection(DB_URL, USER, PASS); 
     System.out.println("Connected database successfully..."); 

     //STEP 4: Execute a query 
     System.out.println("Creating statement..."); 
     stmt = connec.createStatement(); 

     // Step 2: To update the database with the new count and the netppe values. 

     // Step to know whether the ID is present or not in the database 
     for(int i=0;i<identities.length;i++){ 
     String booleanString = "SELECT 1 FROM cgm_counters WHERE id = "+identities[i]; 

stmt.execute(booleanString); 
     ResultSet resultSet = stmt.getResultSet(); //result set for records 
     boolean recordFound = resultSet.next(); 
     ResultSet rs = null; 
// Retrieve the 'netppe' information. 
     if(recordFound){ 

      String sql = "SELECT * FROM cgm_counters WHERE id="+identities[i]; 
      rs = stmt.executeQuery(sql); 
      while(rs.next()){ 
       //Retrieve by column name 
       double net_ppe = rs.getDouble("spend"); 
       System.out.println("The value of the netppe :"+net_ppe); 
      } 

}// end of 'If' statement 

에 대한 코드의 일부를 게시하고있다.

1 > I want to see whether the ID is present or not in the database 
2 > If ID - present 
{ 
2 a > retrieve the 'netppe' information for that particular ID 
2 b > retrieve the 'count' information for that same ID 
2 c> Update the database with the new 'netppe' and 'count' value for the same ID 
} else { 
Insert the information for the new ID 
} 

각 ID에 대한 연결을 종료하지 않고 모든 명령문을 실행하는 방법은 무엇입니까? JDBC 및 SQL 입문. 어떤 도움을 주셔서 감사합니다.

+0

은 jdbc 배치를 사용합니다. – Kick

+0

왜 ID마다 연결을 닫아야합니까? 연결을 닫지 않는 코드가 이미 있습니까? – eis

+0

@eis는 'rs.close()'문을 제거했으며 연결을 닫지 않고 여러 문을 실행하는 경우 동일한 단계를 수행합니까? – user3188390

답변

4

좋아, 코드에 많은 문제가 있습니다. 먼저 떨어져,

//STEP 2: Register JDBC driver 
Class.forName("com.mysql.jdbc.Driver"); 

당신은 인터페이스 자체가 아닌 드라이버 구현을 통과해야합니다. 좋은 소식은이 코드가 JDBC 4.0에서 불필요하다는 것입니다. 이미 클래스 경로를 검색하여 드라이버를 찾습니다.

둘째, 각 쿼리에서 연결이 닫히지 않습니다. 코드 어디에도 connec.close()이라고 부르는 곳이 없습니다. JDBC는 연결을 닫지 않습니다.

세 번째로 중첩 된 for 루프에서는이 작업을 수행 할 필요가 없습니다. 그것은 끔찍한 생각입니다. SQL 쿼리와 JDBC에 대한 당신의 개념은 약간의 선명함을 필요로합니다. 다음을 간단히 수행 할 수 있습니다.

for(int i=0;i<identities.length;i++) { 
    String sql = "SELECT * FROM cgm_counters WHERE id="+identities[i]; 
    ResultSet rs = stmt.executeQuery(sql); 
    while(rs.next()){ 
     //Retrieve by column name 
     double net_ppe = rs.getDouble("spend"); 
     System.out.println("The value of the netppe :"+net_ppe); 
    } 
} 

배치 쿼리를 수행하는 것이 더 좋을 것입니다.

String batch = "("; 
for (int i = 0; i < identities.length;i++) { 
    if (i < identities.length() - 1) 
     batch += "?, "; 
    else 
     batch += "?)" 
} 

String sql = "SELECT * FROM cgm_counters WHERE id in " + batch; 
ResultSet rs = stmt.executeQuery(sql); 
while(rs.next()) { 
    double net_ppe = rs.getDouble("spend"); 
    System.out.println("The value of the netppe :"+net_ppe); 
} 

각 ID 테이블에 있는지 여부를 "확인"을 쿼리의 예선을하고있는 것 같다,하지만이 필요하지 않습니다. ID가 테이블에 없으면 대가로 빈 결과 집합을 얻습니다. 빈 결과 집합에는 아무 문제가 없습니다. rs.next()이 false를 반환하기 때문에 while 루프는 결코 실행되지 않습니다. 비어 있는지 여부도 rs.first()으로 전화하여 확인할 수 있습니다. 이 방법은 커서를 움직이지 않습니다.

+0

제안 및 도움에 감사드립니다. 만약 내가 몇 가지 질문을한다면 나는 필요할 때 도움을 얻을 수 있기를 바랍니다. – user3188390

관련 문제