2017-01-19 200 views
0

這是我的代碼,我希望兩個數據到我的數據庫,但是當我僅進行最後一排或第二排數據集到我的數據庫表:如何將表的多行數據插入到數據庫中?

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對象。爲什麼?

(因此,你也有許多不同的PreparedStatement對象,你有行有多少,哪一個將你的循環結束後,實際執行?)

0

初始化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()); 
} 
相關問題