Java中有类似mysql_num_rows的东西吗?

时间:2014-12-15 17:21:01

标签: java mysql

我正在用Java编写一个简单的程序来连接MySQL。我尝试编写一个简单的查询,只检查用户名和密码(运行程序时由我输入​​)是否在我的数据库中。

由于我没有那么多使用JDBC的经验,我想知道Java是否有类似PHP mysql_num_rows的方法,以检查我的数据库中是否有特定的信息。

2 个答案:

答案 0 :(得分:1)

使用JDBC,只需使用正确的SQL查询向数据库发送SELECT语句即可 然后你会得到一个ResultSet。然后检查它是否有任何行或它有哪些行 基于此,您可以确定用户记录是否存在。

ResultSet

答案 1 :(得分:1)

使用简单的SELECT语句:

String username = "..."; //the username, it could be a method parameter
String password = "..."; //the password, it could be a method parameter
Connection con = .... //retrieve the connection the way you're doing it now
//replace ... for the data you want/need from user
String sql = "SELECT ... FROM user WHERE name = ? and password = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
    //read the data from ResultSet
}
rs.close();
pstmt.close();
con.close();
相关问题