批量查询
在开发项目中我们会经常遇到批量插入, 批量更新, 然后批量查询和批量删除比较少见,但是也有,这章就介绍一下批量查询
1.批量查询最简便的方法就是循环sql语句查询,懂点基础的都会,列如:
StringBuilder sql = new StringBuilder(128).append("select").append(verbosity.getColumnSelectFragment()).append("from")
.append(TABLE.nameAndAlias).append("where").append(COLUMN.ID.aliasAndName).append("=").append("=?");
if (log.isLoggable(Level.FINEST))
{
log.log(Level.FINEST, sql.toString());
}
ps = conn.prepareStatement(sql.toString());
for (int j = 0; j < officeIdList.size(); j++)
{
ps.setLong(1, officeIdList.get(j));
rs = ps.executeQuery();
}
while (rs.next())
{
officeList.add(verbosity.prepare(rs));
}
}
上面的循环 能实现批量查询 但是每次查询都会跟数据库交互,查询很多数据时效率是非常低的, 工作一段时间的程序员都不会用这个
2.用到 数据库中的关键字 in 吧sql语句循环拼接出来,只跟数据库交互一次,效率会提高很多
StringBuilder sql = new StringBuilder(128).append("select").append(verbosity.getColumnSelectFragment()).append("from")
.append(TABLE.nameAndAlias).append("where").append(COLUMN.ID.aliasAndName).append("in").append("(");
for (int i = 0; i < idArray.length; i++)
{
sql.append("?");
if (i < idArray.length - 1)
{
sql.append(",");
}
}
sql.append(")");
if (log.isLoggable(Level.FINEST))
{
log.log(Level.FINEST, sql.toString());
}
ps = conn.prepareStatement(sql.toString());
int i = 1;
for (long id : idArray)
{
ps.setLong(i++, id);
}
rs = ps.executeQuery();
while (rs.next())
{
t = verbosity.prepare(rs);
list.add(t);
}