You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java JDBC中检查数据库是否存在指定乘客ID?

问题:如何判断PostgreSQL查询结果中是否存在指定ID的乘客?

我编写了一段Java代码用于从PostgreSQL数据库的passageiros表中查询指定ID的乘客信息,代码如下:

import java.sql.*;
import java.io.*;

public class VerInformacaoPassageiro {

    public static void main(String args[]) {
        String dbname = "BD22";
        String dbuser = "postgres";
        String password = "12345";
        String url = "jdbc:postgresql://localhost:5432/" + dbname;

        try {
            BufferedReader in;
            in = new BufferedReader( new InputStreamReader( System.in ));
            System.out.print("Numero de identificacao: ");
            String identificacao = in.readLine();

            Connection c = DriverManager.getConnection(url, dbuser, password);
            c.setAutoCommit(false);
            Statement stmt = c.createStatement();
            String query = "SELECT nomeP, sexo, destinopretendido, dataviagem " +
                    "FROM passageiros " +
                    "WHERE nidentificacao='" + identificacao + "';";
            System.out.println("QUERY: " + query);
            ResultSet rs = stmt.executeQuery(query);
            System.out.println( "Informacao do passageiro com numero de identificacao " + identificacao);
            System.out.println( "---------------------------------------");
            while ( rs.next() ) {
                int nidentificacaoP = rs.getInt("nidentificacao");
                String nome = rs.getString("nomeP");
                String sexo = rs.getString("sexo");
                String destinopretendido = rs.getString("destinopretendido");
                String dataviagem = rs.getString("dataviagem");
                if (nidentificacaoP == NULL)
                    System.out.print("Identificacao nao encontrada");
                else
                    System.out.println( nome + " do sexo "  + sexo + " para o destino " + destinopretendido + " no dia " + dataviagem );
            }

            rs.close();
            stmt.close();
            c.close();
        }
        catch (Exception e) {
            System.err.println( e.getClass().getName()+": "+ e.getMessage() );
            System.exit(0);
        }
    }
}

但我在以下代码段存在疑问:

if (nidentificacaoP == NULL)
        System.out.print("Identificacao nao encontrada");
    else
        System.out.println( nome + " do sexo "  + sexo + " para o destino " + destinopretendido + " no dia " + dataviagem );
}

rs.close();
stmt.close();
c.close();

我的目标是查询数据库中是否存在某一乘客ID,若该ID不存在则输出“ID未找到”,但不知道如何正确编写判断逻辑(当前代码中用NULL占位),请问应该如何修改if条件来实现该功能?


解决方案

1. 修正原代码的核心问题

  • 你的SQL查询语句未选中nidentificacao字段,调用rs.getInt("nidentificacao")会直接抛出SQLException,因为结果集中不存在该列。
  • Java的int是基本数据类型,无法存储null值,即使数据库字段为null,rs.getInt()也会返回0,需用rs.wasNull()判断是否为实际null,但这不是判断ID是否存在的最优方式。

2. 正确判断逻辑:检查ResultSet是否有数据

当查询不到匹配ID时,ResultSet的next()方法会返回false,不会进入循环。可以通过标记变量判断是否找到数据:

// 获取ResultSet后初始化标记
boolean found = false;
System.out.println( "Informacao do passageiro com numero de identificacao " + identificacao);
System.out.println( "---------------------------------------");
while ( rs.next() ) {
    found = true; // 进入循环说明找到匹配数据
    String nome = rs.getString("nomeP");
    String sexo = rs.getString("sexo");
    String destinopretendido = rs.getString("destinopretendido");
    String dataviagem = rs.getString("dataviagem");
    System.out.println( nome + " do sexo "  + sexo + " para o destino " + destinopretendido + " no dia " + dataviagem );
}

// 循环结束后根据标记输出结果
if (!found) {
    System.out.println("Identificacao nao encontrada"); // 或替换为“ID未找到”
}

3. 额外优化:规避SQL注入风险

原代码直接拼接用户输入到SQL语句中,存在严重的SQL注入风险,建议改用PreparedStatement实现参数化查询:

// 替换原Statement相关代码
String query = "SELECT nomeP, sexo, destinopretendido, dataviagem FROM passageiros WHERE nidentificacao=?;";
PreparedStatement pstmt = c.prepareStatement(query);
pstmt.setString(1, identificacao); // 绑定参数
ResultSet rs = pstmt.executeQuery();

修改后的完整代码示例

import java.sql.*;
import java.io.*;

public class VerInformacaoPassageiro {

    public static void main(String args[]) {
        String dbname = "BD22";
        String dbuser = "postgres";
        String password = "12345";
        String url = "jdbc:postgresql://localhost:5432/" + dbname;

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Numero de identificacao: ");
            String identificacao = in.readLine();

            Connection c = DriverManager.getConnection(url, dbuser, password);
            c.setAutoCommit(false);
            
            // 使用PreparedStatement避免SQL注入
            String query = "SELECT nomeP, sexo, destinopretendido, dataviagem FROM passageiros WHERE nidentificacao=?;";
            PreparedStatement pstmt = c.prepareStatement(query);
            pstmt.setString(1, identificacao);
            
            System.out.println("QUERY: " + query.replace("?", "'" + identificacao + "'"));
            ResultSet rs = pstmt.executeQuery();
            
            System.out.println( "Informacao do passageiro com numero de identificacao " + identificacao);
            System.out.println( "---------------------------------------");
            
            boolean found = false;
            while (rs.next()) {
                found = true;
                String nome = rs.getString("nomeP");
                String sexo = rs.getString("sexo");
                String destinopretendido = rs.getString("destinopretendido");
                String dataviagem = rs.getString("dataviagem");
                System.out.println( nome + " do sexo "  + sexo + " para o destino " + destinopretendido + " no dia " + dataviagem );
            }

            if (!found) {
                System.out.println("Identificacao nao encontrada");
            }

            rs.close();
            pstmt.close();
            c.close();
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
    }
}

内容的提问来源于stack exchange,提问作者andre Sousa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 13:43:04