Home > Net >  Error: com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range
Error: com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range

Time:06-15

I have a function to update the user's information as follows:

public void updateAccount(String username, String name, String address, String aboutMe, String 
id) {
    String sql = "update Account set username = '?', \n"
              "                [Full_Name] = '?',\n"
              "                [Address] = '?',\n"
              "                [about_me] = '?'\n"
              "                where id = ?";
    try {
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, username);
        ps.setString(2, name);
        ps.setString(3, address);
        ps.setString(4, aboutMe);
        ps.setString(5, id);
        ps.executeUpdate();

    } catch (Exception ex) {
        Logger.getLogger(AccountDao.class.getName()).log(Level.SEVERE, null, ex);
    }
}

and this code is giving me an error like this: 

Severe: com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.

at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:933) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:948) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1578) at dao.AccountDao.updateAccount(AccountDao.java:117) at controller.UserProfileController.doPost(UserProfileController.java:91)

I don't understand why it gives me the error "The index 2 is out of range" and is there any way to fix it?

CodePudding user response:

Don't enclose ? parameter markers in quotes. These are typed by the appropriate setter:

String sql = "update Account set username = ?, \n"
          "                [Full_Name] = ?,\n"
          "                [Address] = ?,\n"
          "                [about_me] = ?\n"
          "                where id = ?";
  • Related