I`m building a decision support system in java. Below is a part of code, that scans the search word that is typed in by user, then compares it with database searchlog.searchcolumn values and if the word is not there creates a new entry. BUT in the if statement i want it to check for the entry, and if it IS already in searchlog.searchcolumn column, then I want it NOT to create a new duplicate entry, but to add +1 value to searchlog.counter column for the specific word.
for example if search word is “UMBRELLA” and there is already one entry for umbrella in database, i want it to add +1 to counter column in UMBRELLA row.
the purpose of this, is to store all searchwords and keep a track of the most popular ones.
Thank you for your time
String CheckSearch = “SELECTsearchcolumn FROMsearchlog”;
String InsertColumn = "INSERT INTO `mydb`.`searchlog` (`searchcolumn`) VALUES ('"+ InputScanner + "');
//
if (InputScanner.equals(CheckSearch))
System.out.println("value ealready exist, counter well be updated");
else
stmt.executeUpdate(InsertColumn);
EDIT
Thank you for advice of using PreparedStatement, but this is my first more or less serious challenge and for this time, let`s just ignore vulnerability of my code. Thanks
What database are you using? If you are using MySQL, then you should look into
INSERT ... ON DUPLICATE KEY UPDATEstatement. (Other SQL databases haveMERGE, which I’m less familiar with.) Here is the MySQL Documentation.You will need make your
searchcolumnaUNIQUEorPRIMARYcolumn, then something along the lines of:will accomplish what you want.