我有以下查询,我想从两个表中选择数据库中的某些行:
select u.person_id,u.email_address
from xx_e_portal_users u, xx_dummy_person_prod per
where u.person_id = per.person_id
and u.email_address like '%john%'
当我在Toad中运行此查询时,我得到两行。当我使用预准备语句运行相同的查询时,我只获得一行。
以下是我用来从数据库中选择行的Java代码:
activeUsers = "select u.person_id,u.email_address from xx_e_portal_users u, xx_dummy_person_prod per where u.person_id = per.person_id and u.email_address like '%john%'";
connection = getConnection();
PreparedStatement ps = connection.prepareStatement(activeUsers,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
//ps.setString(1, "15");
//ps.setInt(1, 7);
ResultSet rs = ps.executeQuery();
rs.last();
count = rs.getRow();//ERROR:Actual rows - 1, always
rs.beforeFirst();
我在这里做错了什么?
答案 0 :(得分:3)
不要这样做:
rs.last();
它会将查询的光标移动到最后一行,因此结果只会是一行。请注意,并非所有结果集都是可滚动的,因此您无法随意跳转到结尾并返回到开头。
但是,你必须这样做:
rs.next();
在你获得第一行之前。通常你会循环执行此操作:
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// Get the columns of the current row
String personId = rs.getString(1);
String emailAddress = rs.getString(2);
// Do whatever needs to be done with these values
}