I have a column in my database which just contains a counter value. The value should be 1 if the entry is new, otherwise it will either be incremented or decremented if the entry is being updated.
I am trying to figure out how to use the java.sql.PreparedStatement for this purpose.
It is to my understanding that the SQL query which eventually has to be created has to look like:
INSERT INTO `DropletNames` (`Title`,`Count`) VALUES ('Travel to Mars',Count + 1)
My question is: how do I create this query? (fyi: I know the Count + 1 is sort of irrelevant here, since INSERT should always set it to 1, but I am trying to use the same syntax for INSERT as I would for UPDATE)
I tried doing the following:
String query = "INSERT INTO `DropletNames` (`Title`,`Count`) VALUES (?,?)";
PreparedStatement stm = con.prepareStatement(query);
stm.setString(1,"Travel to Mars");
stm.setString(2,"Count + 1"); // I used this because I couldn't find a better way of setting this
However, that obvious produces the wrong result, because it attempts to insert "Count + 1" as a String, instead of evaluating Count + 1.
The only other way I can think of doing it is:
String query = "INSERT INTO `DropletNames` (`Title`,`Count`) VALUES (?,Count + 1)";
PreparedStatement stm = con.prepareStatement(query);
stm.setString(1,"Travel to Mars");
But I am unsure if that violates the "best practices" rules for using the PreparedStatement's setter methods when building the SQL Statement. I cannot see how that would leave me open to SQL injection or other vulnerabilities, but maybe there is something I haven't considered.
Is there a way to do this using the PreparedStatement class, or is my second solution the way I should do this?