获取数据库中的总记录

时间:2014-03-31 16:56:36

标签: rowcount

public ResultSet getRecordsCount(){
    ResultSet result = null;
    try {
        result = statement.executeQuery("Select count(word) from records");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return result;
}

我正在尝试获取数据库中的总行数,但它返回了垃圾值。 我正在使用SQL Server 2012,代码中没有例外。 我的代码是否正确?

1 个答案:

答案 0 :(得分:0)

我会使用这段代码:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public static void main(String[] args) {

  int numRows = 0; 

  try {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    String userName = "user"; //in case you need
    String password = "password"; // in case you need
    String url = "jdbc:microsoft:sqlserver://localhost:1433"+";databaseName=THE_NAME_OF_MY_DB";
    Connection con = DriverManager.getConnection(url, userName, password);
    // if you don't need user and password then
    // Connection con = DriverManager.getConnection(url);

    String SQL = "SELECT * FROM table_name";
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(SQL);
    ResultSetMetaData rsMetaData = rs.getMetaData();

    // This while loop is to loop over each row and the for loop
    // is to loop over each field
    while (rs.next()) {

      for(int i=1; i <= rs.getColumnCount(); i++){

        numRows ++;
        System.out.println(rs.getString(i));
        //This prints field by field
      }
    }

    System.out.println(Total column number"+rs.getColumnCount());
    System.out.println(Total row number"+Integer.toString(numRows));

    rs.close();
    stmt.close();
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}