SQL异常:UcanaccessConnection.prepareStatement的意外标记

时间:2018-02-02 11:38:21

标签: java sql ucanaccess

在此代码中,我正在检查数据库中是否有具有特定ID的记录。如果未找到ID,则将使用新记录更新数据库:

public void save() throws SQLException {
    String checkSQL = "Select count(*) as count from people where id=?";
    PreparedStatement checkStatement = con.prepareStatement(checkSQL);

    String insertSQL = "insert into people (ID, NAME, NI_NUMBER, NI_CAT, MOBILE_NUM, EMAIL, ADDRESS, AREA, POSTCODE) values(?, ?, ?, ?, ?, ?, ?, ?, ?) )";
    PreparedStatement insertStatement = con.prepareStatement(insertSQL);

    for (Employee person : people) {
        int id = person.getId();
        String name = person.getName();
        String NINumber = person.getnINumber();
        NICatagory cat = person.getnICatagory();
        String mobileNumber = person.getMobileNum();
        String email = person.getEmail();
        String address = person.getAddress();
        String area = person.getArea();
        String postcode = person.getPostCode();

        checkStatement.setInt(1, id);

        ResultSet checkResult = checkStatement.executeQuery();
        checkResult.next();

        int count = checkResult.getInt(1);

        if (count == 0) {
            System.out.println("Inserting person with id " + id);

            int col = 1;
            insertStatement.setInt(col++, id);
            insertStatement.setString(col++, name);
            insertStatement.setString(col++, NINumber);
            insertStatement.setString(col++, cat.name());
            insertStatement.setString(col++, mobileNumber);
            insertStatement.setString(col++, email);
            insertStatement.setString(col++, address);
            insertStatement.setString(col++, area);
            insertStatement.setString(col++, postcode);

            insertStatement.executeUpdate();

        } else {
            System.out.println("Updating person with id " + id);
        }

    }
    insertStatement.close();
    checkStatement.close();
}

编译后,我收到THIS错误

任何想法如何解决这个问题?有人建议我在列名称周围使用括号,但这并没有解决我的问题。我也看到了使用 Statement 而不是 PreparedStatement 的建议,但我不知道如何实现它,因为它不允许 checkStatement.setInt(1,id) ;

1 个答案:

答案 0 :(得分:2)

在insert语句的末尾有一个额外的)

String insertSQL = "....... ?, ?, ?, ?, ?, ?, ?, ?) )"; 
                                                    ^
                                                    | here

应该是:

String insertSQL = "....... ?, ?, ?, ?, ?, ?, ?, ?)";