如何在jsp中选择最后一行数据库?

时间:2015-05-28 18:52:32

标签: java database

我无法在jsp中显示数据库的最后一行。我已经尝试打印rs.getString(1),但它不起作用。

ResultSet rs = st.executeQuery("Select MAX(CustomerID) from Customer");  
while(rs.next()){out.print(rs.getString(1));}

1 个答案:

答案 0 :(得分:1)

我不知道这是否是你想要的,但如果你想要获得整行,有一些方法可以实现这一目标

ResultSet rs = st.executeQuery("select max(customerid) as id from customer");
rs.next();
String id = rs.getString("id");
rs = st.executeQuery("select field_a, field_b from customer where customerid = " + id);
rs.next();
String row = id + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);

当然,您需要将field_afield_b列替换为customer表格中的列,并根据需要添加或删除列。

较短的方法是使用order bylimit这样的关键字

ResultSet rs = st.executeQuery("select customerid, field_a, field_b from customer order by customerid desc limit 1");
rs.next();
String row = rs.getString("customerid") + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);

确保向primary key列添加uniquecustomerid约束,以提高两种方法的效果。