简体   繁体   English

如何将在JDBC中执行的SQL查询的结果分配给java变量?

[英]How do I assign the result of an SQL query executed in JDBC to a java variable?

I have a student table with columns email, password, and a variable Result which can either hold a value "pass" or "fail". 我有一个学生表,其中包含电子邮件,密码和变量Result列,它们可以包含值“通过”或“失败”。 I'm executing this statement first in java using JDBC to find the result of a particular student when their email is passed. 我首先在Java中使用JDBC执行此语句,以在特定学生的电子邮件通过时查找其结果。

String sql = "SELECT result FROM hr.student WHERE email = '"+email+"'";

conn = getConnection();
stmt = conn.prepareStatement(sql);

The value returned will either be "pass" or "fail". 返回的值将是“通过”或“失败”。 I want to store the returned value in a variable to use it for an if-else statement. 我想将返回的值存储在变量中,以用于if-else语句。 (if result is "pass", --statements-- else --statements--) (如果结果为“通过”,则-陈述-否则-陈述-)

How do I do this? 我该怎么做呢?

You can do it like : 您可以像这样:

ResultSet rs = stmt.executeQuery(sql);
String result = null;
if (rs.next()) { // replace 'if' with 'while' to iterate if multiple records
    result = rs.getString("result");
}

if you have more records, you can replace if with while and can iterate over ResultSet . 如果有更多记录,则可以将if替换为while并可以遍历ResultSet

For the complete working example you can go through the example here. 对于完整的工作示例,您可以在此处进行遍历

I'd recommend to create the prepared statement as follows: 我建议创建准备好的语句,如下所示:

String sql = "SELECT result FROM hr.student WHERE email = ?";
conn = getConnection();
stmt = conn.prepareStatement(sql);
stmt.setString(1,email)

and then proceed as shown above 然后如上所示继续

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM