2

我正在尝试将用户输入到 jtextfield 中的数据插入到 msaccess 数据库中。当我尝试执行我的 sql 语句时,我收到一条错误,指出 INSERT INTO 语句中的语法错误。我检查了我的 sql 语句并尝试了一些不同的方法,但似乎找不到任何类型的语法错误。

    conn = Connect.ConnectDB();
    String sql = "insert into Team ("
            +"TeamID,"
            +"TeamCity,"
            +"TeamMascot,"
            + "values("+txtid.getText()+ ",'"+txtname.getText()+"','"+txtaddress.getText()+"')" ;
    try{
        pst = conn.prepareStatement(sql);
        pst.execute();
        JOptionPane.showMessageDialog(null, "Entry " + txtid.getText() + " Saved");
        UpdateJTable();
        //conn.close();
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
4

1 回答 1

0

错误是关键字之前的额外逗号和没有右括号values

String sql = "insert into Team ("
            +"TeamID,"
            +"TeamCity,"
            +"TeamMascot,"    // <<== HERE, change comma into closing parenthesis

顺便说一句,您的陈述很容易受到SQL Injection. 如果参数化了值,则可以避免它。例如,

String sql = "insert into Team (TeamID,TeamCity,TeamMascot) values (?, ?, ?, ?)"
pst = conn.prepareStatement(sql);
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
于 2013-04-25T11:56:41.030 回答