我正在尝试从 mysql 表中获取数据。当我在 phpmyadmin 上手动运行时,我的查询返回一个值,但当我从 Java 代码运行时,它给出一个空集。这是查询:
SELECT real_name
from doctorlogin
where password='1234' and id='X11111X';
代码:
public ArrayList<ArrayList<String>> query(String statement) throws SQLException {
ResultSet rs = stmt.executeQuery(statement);
int numcols = rs.getMetaData().getColumnCount();
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
if (rs.isBeforeFirst()) {
do {
ArrayList<String> row = new ArrayList<String>(); // new list per row
int i = 0;
while (i <= numcols) { // don't skip the last column, use <=
row.add(rs.getString(i++));
}
result.add(row); // add it to the result
} while (rs.next());
}
return result;
}
public String login(String username, String password, String domain) throws SQLException {
String query = "SELECT real_name from " + domain + "login where password='" + password + "' and id='" + username + "';";
System.out.println(query);
ArrayList<ArrayList<String>> r = query(query);
if (r.size() > 1 || r.size() == 0)
return "Login Failed";
else
return r.get(0).get(0);
}
进行编辑后,即使我在 phpmyadmin 中得到一行,代码仍然无法获取任何结果。
public ArrayList<ArrayList<String>> query(String statement) throws SQLException {
ResultSet rs = stmt.executeQuery(statement);
int numcols = rs.getMetaData().getColumnCount();
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
while ( rs.next() ) {
ArrayList<String> row = new ArrayList<String>(); // new list per row
for ( int i = 1; i <= numcols; i++ ) {
row.add(rs.getString(i));
}
result.add(row); // add it to the result
}
return result;
}
phpmyadmin 查询截图 -> https://drive.google.com/drive/folders/0B_yqoCAAV2rFdDZqUzlmeXljNWs
最佳答案
在调用rs.next()
之前,您无法从行中检索信息。因此 ResultSet
循环的常用格式很简单
while (rs.next()) {
// Retrieve the column values
}
那里不需要 if
语句。如果没有返回行,则 if
为 false,并且您将返回一个空列表。但上面的简单 while
也是如此。不需要 do...while()
- 您首先需要移动光标,然后才读取值。
最后,列的索引从 1 开始,而不是从 0 开始。因此您的 i
应该从 1 开始。但是为什么不将其替换为 for
循环而不是 同时
?
while ( rs.next() ) {
ArrayList<String> row = new ArrayList<String>(); // new list per row
for ( int i = 1; i <= numcols; i++ ) {
row.add(rs.getString(i));
}
result.add(row); // add it to the result
}
您应该阅读ResultSet
documentation因为信息就在那里。
关于java - 从结果集中提取时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32932872/