2017-10-17 26 views
1

有一個名爲good_inin_quantityin_idgood_codein_group,SQLite表,in_VATPaid源碼Java的查詢不會插入到表

這裏是我的表例如 enter image description here

,並有方法將記錄插入到它

public static void inputGoods(GoodsInput goodsinput){ 
    String goodCode = goodsinput.getInGood().getGood_code(); 
    int goodBatch = goodsinput.getInGroup(); 
    int goodQuantity = goodsinput.getInQuantity(); 
    double goodVATPaid = goodsinput.getInVatPaid(); 
    String sqlInsert = "INSERT INTO good_in (good_code, in_group, in_quantity, in_VATPaid)" 
      + " VALUES ('" + goodCode + "', " + "'" + goodBatch + "', " + "'" + goodQuantity 
      + "', " + "'" +goodVATPaid + "');"; 
    System.out.print(sqlInsert); 
    Connection conn = ConnectionFactory.ConnectDB(); 
    try{ 
     Statement statement = conn.createStatement(); 
     statement.executeUpdate(sqlInsert); 
    } 
    catch(SQLException e){ 
    } 
} 

連接類別

 public static Connection ConnectDB(){ 
    try{ 
    Class.forName("org.sqlite.JDBC"); 
    Connection con = DriverManager.getConnection("jdbc:sqlite:kahuyq.db"); 
    return con; 
    } catch (HeadlessException | ClassNotFoundException | SQLException ex){ JOptionPane.showMessageDialog(null, ex); } 
    return null; 

} 

當我將打印的查詢複製到sqlite管理器它添加行,但從java它結束程序沒有錯誤,但不會將行添加到我的表。 有什麼不對?

也有檢查的天氣good_code存在於表good其中只有2列idgood_code,如果不存在,增加了它的其他方法。此方法可從GoodsInput構造函數訪問。當我從構造函數中刪除該方法時,其他方法正常工作。 這裏是方法

public static void insertGoods(Good g){ 
    String sqlSelect = "Select * from good where good_code = '" 
      + g.getGood_code() + "'" ; 
    String sqlInsert = "INSERT INTO good (good_code)" 
      + "VALUES ('" + g.getGood_code() +"')"; 
    Connection conn = ConnectionFactory.ConnectDB(); 
    try{ 
     Statement statement = conn.createStatement(); 
     ResultSet rs = statement.executeQuery(sqlSelect); 


     while(!rs.next()){ 
      statement.executeUpdate(sqlInsert); 
      break; 
     } 

    } 
    catch(SQLException e){ 
    } 
} 
+0

是否有錯誤?連接如何構建? – Lokesh

+0

沒有錯誤,連接是以這種方式構建的public static Connection ConnectDB(){ 嘗試Class.forName(「org.sqlite.JDBC」); Connection con = DriverManager.getConnection(「jdbc:sqlite:kahuyq.db」); return con; (HeadlessException | ClassNotFoundException | SQLException ex){ } JOptionPane.showMessageDialog(null,ex); } return null; } – Sargis

+0

您確定連接有效嗎? –

回答

0

嘗試的語句執行後添加

conn.commit(); 

+0

它增加了一行,但如果我重複添加它不添加相同的對象。表列可能有問題? – Sargis

+0

你有錯誤?你的桌子的主要關鍵是什麼? 您是否在每次添加之後做了一次提交,或者一次又一次? –

+0

我沒有錯誤,PK是in_id與自動增量,我沒有做任何提交,但@Florian Huc寫道時,我將它添加到每個方法的執行結束。而且我還沒有關閉我的連接。它可能是這個問題嗎? – Sargis