Distinguish between the zero value in the column and as result of the query

时间:2015-06-25 18:37:14

标签: java mysql jdbc

I am tryin to get the min speed value of my records where I have the case the value of the speed is equal 0 in the column speed but I have the case too where the result of my query is 0 because there was no min speed found in the range of 40 meter. How can I distinguish between the both cases?

Code:

    String sql_min_speed = "SELECT mac, stop_name, stop_distance, speed from behaviour "
            + "where stop_distance < 40 and mac = ? and stop_name = ? order by speed LIMIT  1";

    int minSpeed = get_min_speed(macD, con, sql_min_speed, stopName,
            maintain);

get_min_speed method:

private int get_min_speed(String macD, Connection con, String sql,
        String stopName, List<Maintain> maintain) throws SQLException {
    PreparedStatement prepared1 = con.prepareStatement(sql);
    prepared1.setString(1, macD);
    prepared1.setString(2, stopName);
    ResultSet rsBehav1 = prepared1.executeQuery();
    int min_speed = 0;
    while (rsBehav1.next()) {
        String mac = rsBehav1.getString("mac");
        String Stname = rsBehav1.getString("stop_name");
        int distance = rsBehav1.getInt("stop_distance");
        min_speed = rsBehav1.getInt("speed");
        Maintain main1 = new Maintain(mac, Stname, distance, min_speed);
        maintain.add(main1);

    }
    return min_speed;
}

2 个答案:

答案 0 :(得分:3)

Change int min_speed = 0; to int min_speed = -1;

Then add a condition in caller method.

答案 1 :(得分:1)

You can either return a negative value when there's no actual minimum speed to return, or you can change the return type to Integer and return null in that case.