Java如何获取数据库表的行数
时间: 2023-06-25 09:03:30 浏览: 83
在Java中获取数据库表的行数可以使用JDBC API提供的ResultSet接口的getMetaData()方法和getRow()方法实现。
以下是获取MySQL数据库表行数的示例代码:
```java
import java.sql.*;
public class GetRowCountExample {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM my_table");
rs.next();
int rowCount = rs.getInt(1);
System.out.println("Row count: " + rowCount);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
}
}
```
在该示例代码中,使用了JDBC驱动程序连接MySQL数据库,并执行了一条查询语句获取表的行数。最后将行数输出到控制台。其中,`rs.next()`方法将结果集的游标移到第一行,然后使用`rs.getInt(1)`获取第一列的值即为行数。