I have a Java program that needs to iterate through a HashMap
to get a parameters that are then used to query the MySQL database.
The code is as follows:
Iterator<Entry<String, Double>>it = ws.entrySet().iterator();
Connection con = null;
while(it.hasNext())
{
Entry<String, Double>pairs = it.next();
PreparedStatement ps = con.prepareStatement("select doc_freq from lookup where word=?");
ps.setString(1, pairs.getKey());
ResultSet rs = ps.executeQuery();
}
The process of repeatedly accessing the database for every iteration of the loop (which is about 500 times) is slowing down my application. Is there any way I can send all these parameters at once so that I access the database only once?
Considering ws is a map, you can do a single query that way:
Connection con = getConnection();
Set<String> ks = ws.keySet();
if (ks.size() > 0) {
StringBuilder inStatement = new StringBuilder("?");
for (int i = 1; i < ks.size(); i++) {
inStatement.append(", ?");
}
PreparedStatement ps = con.prepareStatement("select doc_freq from lookup where word in (" + inStatement.toString() + ")");
int k = 1;
for (String key : keySet) {
ps.setString(k++, key);
}
ResultSet rs = ps.executeQuery();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With