【问题标题】:SQL syntax error for my java program我的 java 程序的 SQL 语法错误
【发布时间】:2026-02-17 11:50:02
【问题描述】:

我的代码:

try{ Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lentele", "root", "");
String select = "SELECT * FROM darbuotojai WHERE 1";

    String ID = infoID.getText();
    String Vardas = infoV.getText();
    String Pavardė = infoP.getText();
    String Pareigos = infoPar.getSelectedItem().toString();
    String Alga = infoAlg.getText();
    String Premija = infoPre.getText();

    String insert = "INSERT INTO `darbuotojai`(`ID`, `Vardas`, `Pavardė`, `Pareigos`, `Alga`, `Premija`) VALUES ('"+ID+"','"+Vardas+"','"+Pavardė+"','"+Pareigos+"','"+Alga+"','"+Premija+"',)";


        stm.executeUpdate(insert);
        JOptionPane.showMessageDialog(null, "Užklausa sėkminga");
        infoID.setText("");
        infoV.setText("");
        infoP.setText("");
        infoPar.setSelectedItem("");
        infoAlg.setText("");
        infoPre.setText("");

        display();
    } catch (Exception e) {JOptionPane.showMessageDialog(null, e.getMessage()); }

我得到这样的错误:

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 ')' at line 1.
And ones more: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user ''@'localhost' to database 'lentele'.

请以最简单的方式为初学者解释这些问题。 此代码用于添加按钮,这有助于将信息插入到我的表格中。

【问题讨论】:

  • 删除'"+Premija+"',中的最后一个,

标签: java mysql syntax xampp


【解决方案1】:

去掉右括号前的逗号:

Premija+"',)";

变成

Premija+"')";

除了不要手动构建查询,除非您想容易受到 SQL 注入攻击:使用 PreparedStatement

【讨论】: