Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have a map which holds words and counts as key and value. I want to insert this map into mysql db and if a word is used before want to update its count. Any help would be so appreciated!

What I have tried:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;

public class DatabaseOperations {
	DBConnection conn = new DBConnection();
	Connection con = conn.connDb();
	Statement statement = null;
	PreparedStatement preparedStatement = null;
	ResultSet resultSet = null;

	public void insertSplittedText(HashMap<String, Integer> map) throws SQLException {
		Iterator<String> wordIterator = map.keySet().iterator();
		statement = con.createStatement();
		String sql = ("INSERT INTO words" + "(count, word)" + "VALUES (?,?)");
		preparedStatement = con.prepareStatement(sql);
		while (wordIterator.hasNext()) {
			String key = wordIterator.next();
			String selectQuery = "SELECT * FROM words WHERE word='" + key + "'";
			ResultSet rs = preparedStatement.executeQuery(selectQuery);
			String query = "UPDATE words SET count=? WHERE count=?";
			preparedStatement.executeQuery(query);
			if (rs.next()) {
				int oldCount = rs.getInt(1);
				int newCount = oldCount + map.get(key);
				preparedStatement.setInt(1, newCount);
				preparedStatement.setString(2, key);
			} else {
				preparedStatement.setInt(1, map.get(key));
				preparedStatement.setString(2, key);
			}
		}
	}
}
Posted
Updated 16-Apr-22 1:44am

1 solution

String query = "UPDATE words SET count=? WHERE count=?";
preparedStatement.executeQuery(query);
UPDATE queries do not return values - they return the number of rows that were altered or affected.

You can't use executeQuery for UPDATEs, you need executeUpdate instead
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900