计算mysql语句在java中没有返回正确的值

时间:2015-10-13 11:22:18

标签: java mysql

我从count语句中获得了值9,但是当我在localhost中尝试它时,我得到了18.请帮助我,我被困在这里非常感谢你

这是我的代码

private int getgoods;
String query="Select count(item_id) as 'total' from item_tb";
PreparedStatement pst =conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();

while(rs.next())
{
         getgoods=rs.getInt("total");
}

JOptionPane.showMessageDialog(null, getgoods); 
// supposedly to be 18 but im getting 9

from mysql

from java , Im using eclipse

2 个答案:

答案 0 :(得分:0)

在查询中使用*代替item_id

String query="Select count(*) as 'total' from item_tb";

并使用if(rs.next())代替while循环。

答案 1 :(得分:0)

请尝试以下操作:

ResultSet rs = st.executeQuery("Select count(*) as 'total' from item_tb");
rs.next();
int count = rs.getInt(1);

ResultSet rs = st.executeQuery("Select count(1) as 'total' from item_tb");
rs.next();
int count = rs.getInt(1);