private UUID getClientID(String username) {
try {
String query = "SELECT id FROM `client_table` WHERE username=" + username;
stmt = connection.prepareStatement(query);
ResultSet rs = stmt.getResultSet();
return UUID.fromString(rs.getString(2));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
嗨,这是我的代码和我想要抓取的数据库部分:http://prntscr.com/ezbomi。我想要ID,但它返回null。我认为这是因为查询 - 任何想法?
答案 0 :(得分:1)
ResultSet#next
以获取ResultSet
的下一行(如果存在)1
而不是2
,因为您只需要从1
开始请求单个列和列索引PreparedStatements
,参数并将值绑定到语句try-with-resources
来管理您的资源,并确保在您完成后清理它们Exception
而不是抓住它,它会有更多的意义而不仅仅是回归null
例如
try (PreparedStatement stmt = connection.prepareStatement("SELECT id FROM `client_table` WHERE username=?")) {
stmt.setString(1, username);
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
return UUID.fromString(rs.getString(1));
}
}
看看:
了解更多详情
答案 1 :(得分:0)
您应该在获取数据之前移动ResultSet游标。光标最初指向头部。
rs.next();
return UUID.fromString(rs.getString(2));
答案 2 :(得分:0)
试试这个。丢弃了报价。除非你有充分的理由不这样做,否则你应该总是使用准备好的陈述。您尝试从ResultSet访问第二个元素的任何特殊原因?
private UUID getClientID(String username) {
try {
//drop the extra quotes in the SQL statement
String query = "SELECT id FROM client_table WHERE username = ?";
//added prepared statement
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
ResultSet rs = stmt.getResultSet();
//use 1 to access the first result from the result set
return UUID.fromString(rs.getString(1));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}