无法从结果集中检索值 (jdbc)
在 ResultSet rs = stmt.executeQuery(query);
之后,代码不会执行。因此,变量不会从结果集中获取值。有人能帮我解决这个问题吗?
public User storeTempDetails(String s1){
Statement stmt = null;
String query = "select username, account_no,name from accounts where username = ?";
try {
connection = DriverManager.getConnection(DBurl, DBusername, DBpassword);
System.out.println("Database connected!");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("this line is not printed");
while (rs.next()) {
userName = rs.getString("username");
accountNo = rs.getString("account_no");
name = rs.getString("name");System.out.println("ss"+accountNo);
}
} catch (SQLException e ) {
throw new RuntimeException("Cannot connect the database!", e);
} finally {
User userObj=new User(userName,accountNo,name);
System.out.println("Closing the connection.");
if (connection != null) try { connection.close(); }
catch (SQLException ignore) {}
return userObj;
}
}
After ResultSet rs = stmt.executeQuery(query);
, the code does not execute. Thus, the variables do not get the values from the result set . Can anybody help me resolve this ?
public User storeTempDetails(String s1){
Statement stmt = null;
String query = "select username, account_no,name from accounts where username = ?";
try {
connection = DriverManager.getConnection(DBurl, DBusername, DBpassword);
System.out.println("Database connected!");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("this line is not printed");
while (rs.next()) {
userName = rs.getString("username");
accountNo = rs.getString("account_no");
name = rs.getString("name");System.out.println("ss"+accountNo);
}
} catch (SQLException e ) {
throw new RuntimeException("Cannot connect the database!", e);
} finally {
User userObj=new User(userName,accountNo,name);
System.out.println("Closing the connection.");
if (connection != null) try { connection.close(); }
catch (SQLException ignore) {}
return userObj;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从这样的事情开始。这些实用程序类将使您在开始使用 JDBC 时变得更加轻松:
考虑到这些实用程序,我将如何编写它。我可能会将
User
放在model
包中,而UserDaoImpl
将是其自己的 .java 文件中的公共类。我只是懒:Start with something like this. These are utility classes that will make your life easier when you're starting off with JDBC:
Given those utilities, here's how I might write it. I'd probably put
User
in amodel
package, andUserDaoImpl
would be a public class in its own .java file. I'm just being lazy:有一个异常抛出。但由于
finally
块中的return
,该异常永远不会发生。谷歌搜索“java”、“return”和“finally”,你会感觉到这有多糟糕。修复代码并向我们展示堆栈跟踪。
There is an exception thrown. But that exception will never get anywhere, because of the
return
in thefinally
block. Google for "java", "return" and "finally" and you will get a feeling how bad that is.Fix the code and show us the stacktrace.