2017-01-19 3 views
0

이 내 코드 만 내 데이터베이스에 두 행의 데이터를 원하지만 난 단지 마지막 행 또는 두 번째 행을 진행할 때 데이터가 내 데이터베이스 테이블에 설정합니다테이블의 많은 행 데이터를 DB에 삽입하는 방법은 무엇입니까?

try{ 

int rows=tblCO2.getRowCount(); 

for(int row = 0; row<rows; row++) 
    { 
    System.out.println(row); 
    String itemcode = (String)tblCO2.getValueAt(row, 0); 
    String lotno = (String)tblCO2.getValueAt(row, 1); 
    String stackno = (String)tblCO2.getValueAt(row, 2); 
    String grade = (String)tblCO2.getValueAt(row, 3); 
    String ctns = (String)tblCO2.getValueAt(row, 4); 

    try 
    { 
     Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); 
     conn = DriverManager.getConnection("jdbc:derby://localhost:1527/demo","user","pw"); 
     conn.setAutoCommit(false); 
     String queryco = "Insert into alicreative.pur(itemcode,lotno,stackno,grade,ctns) values (?,?,?,?,?)"; 
     pst = conn.prepareStatement(queryco); 
     pst.setString(1, itemcode); 
     pst.setString(2, lotno); 
     pst.setString(3, stackno); 
     pst.setString(4, grade); 
     pst.setString(5, ctns); 
     pst.addBatch(); 
    } 
    catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) 
    { 
     JOptionPane.showMessageDialog(this,e.getMessage()); 
    } 


} 
pst.executeBatch(); 
conn.commit(); 
} 
catch( HeadlessException | SQLException e){ 
    JOptionPane.showMessageDialog(this,e.getMessage()); 
} 

그래서 나에게 두 개의 데이터 저장 행에 대한 해결책을 말해 하나의 행동.

답변

0

각 행에 대해 새 Connection 개체를 만듭니다. 왜 ?

0

를 초기화 (결과적으로, 당신은 또한 당신이 행이만큼 별개의 PreparedStatement 객체. 어느 실제로 루프의 종료 후 실행됩니다 얼마나 많은 및?해야합니다) 당신의 PreparedStatement (만들 연결하기 전에) 루프가 시작될 때마다 반복 할 때마다 새 루프를 만들고 하나의 배치로 채 웁니다.

마지막으로 PreparedStatement (마지막 행의 배치 만 포함) 만 실행됩니다.

try{ 

int rows=tblCO2.getRowCount(); 

Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); 
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/demo","user","pw"); 
conn.setAutoCommit(false); 
String queryco = "Insert into alicreative.pur(itemcode,lotno,stackno,grade,ctns) values (?,?,?,?,?)"; 
PreparedStatement pst = conn.prepareStatement(queryco); 

for(int row = 0; row<rows; row++) 
{ 
    System.out.println(row); 
    String itemcode = (String)tblCO2.getValueAt(row, 0); 
    String lotno = (String)tblCO2.getValueAt(row, 1); 
    String stackno = (String)tblCO2.getValueAt(row, 2); 
    String grade = (String)tblCO2.getValueAt(row, 3); 
    String ctns = (String)tblCO2.getValueAt(row, 4); 

    try 
    { 

     pst.setString(1, itemcode); 
     pst.setString(2, lotno); 
     pst.setString(3, stackno); 
     pst.setString(4, grade); 
     pst.setString(5, ctns); 
     pst.addBatch(); 
    } 
    catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) 
    { 
     JOptionPane.showMessageDialog(this,e.getMessage()); 
    } 


} 
pst.executeBatch(); 
conn.commit(); 
} 
catch( HeadlessException | SQLException e){ 
    JOptionPane.showMessageDialog(this,e.getMessage()); 
}