我正在尝试访问我的数据库,注入(inject)一些 SQL 代码并从中返回值。
首先,我是这个东西的新手,但我想出了以下代码:
public static ResultSet checkCmdAmount() 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(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
PreparedStatement zpst=null;
ResultSet zrs=null;
zpst=connect.prepareStatement("SELECT COUNT(1) FROM eigenebenutzerbefehle");
zrs=zpst.executeQuery();
return zrs;
}catch (Exception e) {
throw e;
} finally {
close();
}
}
在返回时,我得到以下信息:
ResultSet: com.mysql.jdbc.JDBC4ResultSet@196da649
但我实际上想要表中的行数。 当我通过 phpmyadmin 执行 sql 代码时,我得到 3,这是正确的。
这里有什么问题吗?
最佳答案
您需要从 ResultSet 中读取并获取所需的值。如下所示:
public static int checkCmdAmount() throws Exception {
// ...
int count = 0;
while (zrs.next()) {
// Get the values from the current row...
count = zrs.getInt(1);
}
return count;
}
关于Java:MySQL 查询并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22586273/