In this code, I am checking a database for records with a certain ID. If the ID is not found, the database will be updated with a new record:
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();
}
Upon compiling I receive THIS error
Any ideas how to get around this? Someone suggested i use brackets around the column names however this did not solve my issue. I have also seen a suggestion to use Statement rather than PreparedStatement however im not sure how to implement this as it does not allow checkStatement.setInt(1, id);
You have an additional )
at the end of the insert statement:
String insertSQL = "....... ?, ?, ?, ?, ?, ?, ?, ?) )";
^
| here
That should be:
String insertSQL = "....... ?, ?, ?, ?, ?, ?, ?, ?)";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.