2017-10-14 63 views
0

我試圖從jtable和數據庫一起刪除選定的行,但我收到語法錯誤。可能是因爲我使用varchar或真的在這種情況下語法是錯誤的?嘗試從jtable刪除Java SQL語法錯誤

btnNewButton_2 = new JButton("Dzēst"); 
    btnNewButton_2.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      Statement statement = null; 
      try { 
       int tableRow = table_1.getSelectedRow(); 
       Object Kods = table_1.getValueAt(tableRow, 0); 
       Object Nosaukums = table_1.getValueAt(tableRow, 1); 
       Object Inventara = table_1.getValueAt(tableRow, 2); 
       Object Uzskaites = table_1.getValueAt(tableRow, 3); 
       Object Iegad = table_1.getValueAt(tableRow, 4); 
       Statement stmt = null; 
       Connection connection = ConnectDB(); 


       String sql = "DELETE FROM users " + 
         "WHERE Kods = " + Kods + " AND Nosaukums = '" + Nosaukums + "' AND Inventara Nr = " + 
         Inventara + " AND Uzskaites vertiba = '" + Uzskaites + "' AND Iegades vertiba = " + Iegad; 
       stmt = connection.createStatement(); 
       stmt.executeUpdate(sql); 

      } catch (SQLException ex) { 
       Logger.getLogger(dddddddd.class.getName()).log(Level.SEVERE, null, ex); 
        JOptionPane.showMessageDialog(null, "Nav ievadita visa informacija"); 
      } 

錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Nr = ttttt AND Uzskaites vertiba = '3.0' AND Iegades vertiba = 3.0' at line 1 

數據庫變量:

Kods -Index -int(255)  
Nosaukums - varchar(255)   
Inventara Nr - varchar(255) 
Uzskaites vertiba - float     
Iegades vertiba - float 
+2

我還建議你看一下'PreparedStatement's – MadProgrammer

回答

1

請注意,您的列具有空間分隔的名字。通常使用這種命名約定並不是最佳實踐,但是使用snake_case或CamelCase。

就你而言,你需要正確地引用你的列名,例如

WHERE `Inventara Nr` = '33' 

請注意,儘管您的代碼易受SQL注入攻擊。我建議閱讀有關它們。您應該始終使用PreparedStatements

+0

謝謝,會記住。用snake_case改變了一切,但現在有新的錯誤。 「where子句」中的未知列'ttetetetete'。 – Krichukzz

+0

@Krichukzz所有的字符都必須放在引號中。示例:刪除文檔WHERE content ='Hello World'。但是如前所述,PreparedStatements將爲您的參數使用setString時爲您做到這一點。在你的情況'Inventara Nr'確實是一個varchar,所以它應該在''Inventara Nr'='ttetetetetete'。這可以幫助你使用PreparedStatements:http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html – petul

+0

'String sql =「DELETE FROM users」+ \t \t「WHERE Kods =」+ Kods + 「ANDNosaukums ='」+ Nosaukums +「'AND Inventara_Nr ='」+ \t \t Inventara +「'AND Uzskaites_vertiba =」+ Uzskaites +「AND Iegades_vertiba =」+ Iegad; \t \t stmt = connection.createStatement(); \t \t stmt.executeUpdate(sql); '仍然不想刪除任何東西。即使我把'Nosaukums'和'Inventara_Nr'設置爲quoutes。 – Krichukzz