我创建了这段代码,允许我计算表格中的行数。但是,我无法返回计数的数字,并显示“无法从结果类型为void的方法返回值”。有人能告诉我'我的错误在哪里?非常感谢!
public void num() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from testdb.emg");
int count = 0;
while (resultSet.next()) {
count++;
}
return count;
} catch (Exception e) {
}
答案 0 :(得分:17)
尝试以下代码
public int num() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("select count(*) from testdb.emg");
while (resultSet.next()) {
return resultSet.getInt(1);
}
} catch (Exception e) {
}
以下是错误
public void num() throws Exception {
应该是
public int num() throws Exception {
要计算总行数,您应使用查询select count(*) from testdb.emg
让我知道任何问题。
答案 1 :(得分:4)
更改
public void num() throws Exception {
到
public int num() throws Exception {
您正在从count
类型的变量int
返回值,因此该方法的返回类型也应为int
。
您还应确保在代码的每个执行路径中都有return
语句,包括catch
块中的异常处理程序(或者您将收到“缺少返回语句”错误消息) 。但是,最好避免捕获所有异常的catch
语句(如您的)。此外,忽略(即不处理)catch块中的异常通常会导致难以诊断问题,这是一种不好的做法。
代码还有其他问题:除count
外,没有声明任何变量。
请注意,您可以使用以下SQL语句直接获取行数:
select count(*) from testdb.emg
这可以避免将表testdb.emg
中的所有数据发送到您的应用程序,并且对于大表来说要快得多。
答案 2 :(得分:3)
如何在java中获取count(*)mysql数据表。 试试吧:
public int getRowNumber(){
int numberRow = 0;
Connection mysqlConn = DriverManager.getConnection(HOST, USER_ID, PASSWORD);
try{
mysqlConn.getConnection();
String query = "select count(*) from dataTable";
PreparedStatement st = mysqlConn.preparedStatement(query);
ResultSet rs = st.executeQuery();
while(rs.next()){
numberRow = rs.getInt("count(*)");
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}
return numberRow;
}
答案 3 :(得分:0)
public void num() throws Exception {
应该是
public int num() throws Exception {
答案 4 :(得分:0)
我用Fahim Parker的答案做了些改动
`
public int num() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
statement = connect.createStatement();
resultSet = statement.executeQuery("<your query statement>");
resultSet.last(); //go to last row;
return resultSet.getRow(); //get row number which is equal to rows count
} catch (Exception e) {
}
`