本文介绍了使用不同的参数多次运行相同的选择查询:Mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Java程序,该程序需要遍历HashMap
以获得用于查询MySQL数据库的参数.
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.
代码如下:
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();
}
针对循环的每次迭代(大约500次)重复访问数据库的过程使我的应用程序变慢.有什么办法可以一次发送所有这些参数,以便我只能访问一次数据库?
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?
推荐答案
考虑到ws是一张地图,您可以通过以下方式进行单个查询:
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();
}
这篇关于使用不同的参数多次运行相同的选择查询:Mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!