在Java JDBC中查找rowcount的正确方法

时间:2012-10-27 18:42:00

标签: java jdbc

我尝试过不同的方法来获取java JDBC中的行数,但似乎没有给出正确的结果。我有什么不对的吗?

即使customer表为空,我应该将rowcount设为0,我也不明白为什么我得到一个非零行数值。

方法1 -

query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
rowcount = metaData.getColumnCount();

方法2 -

query = "SELECT * FROM customer WHERE username ='"+username+"'";
rs = stmt.executeQuery(query);
rowcount = rs.last() ? rs.getRow() : 0;

6 个答案:

答案 0 :(得分:15)

请参阅以下代码段:

import java.io.*;
import java.sql.*;

public class CountRows{
    public static void main(String[] args) {
        System.out.println("Count number of rows in a specific table!");
        Connection con = null;
        int count = 0;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
            try {
                Statement st = con.createStatement();
                BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Enter table name:");
                String table = bf.readLine();
                ResultSet res = st.executeQuery("SELECT COUNT(*) FROM "+table);
                while (res.next()){
                    count = res.getInt(1);
                }
                System.out.println("Number of row:"+count);
            }
            catch (SQLException s){
                System.out.println("SQL statement is not executed!");
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:3)

这是我用来获取Java中行数的方式:

String query = "SELECT * FROM yourtable";

Statement st = sql.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
ResultSet = st.executeQuery(query);

int rows = 0
rs.last();
rows = rs.getRow();
rs.beforeFirst();

System.out.println("Your query have " + rows + " rows.";

我希望这对你有所帮助。

问候。

答案 2 :(得分:2)

当您使用不支持TYPE_FORWARD_ONLY的JDBC时,请使用此方法获取rowcount。

Statement s = cd.createStatement();
ResultSet r = s.executeQuery("SELECT COUNT(*) AS rowcount FROM TableName");
r.next();
int count = r.getInt("rowcount");
r.close();
System.out.println("MyTable has " + count + " row(s).");

您可以使用上述方法获取行计数。

谢谢..

答案 3 :(得分:1)

在Android中,没有结果会返回错误。因此,在增加中的计数之前检查这种情况,而(resultset.next())

if(resultset!=null)
{
//proceed with incrementing row count function
}
else
{
// No resultset found
}

答案 4 :(得分:0)

  

只需迭代并计数

ResultSet result = sta.executeQuery("SELECT * from A3");
            int k=0;
            while(result.next())
                k++;

            System.out.print(k); //k is the no of row

答案 5 :(得分:-1)

由于方法名称指定metaData.getColumnCount()将返回结果集中的总列数,但不会返回总行数(计数)。