有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

NumberFormatException,因为在准备好的Java语句上无法识别NULL

我正在使用准备好的语句插入到我的数据库中。我插入的一些值是空的,因为比赛还没有开始,所以分数是空的,空的

void insertFixtures(List<String[]> fixtures) throws SQLException {
    String query = "REPLACE INTO games (team1_id, team2_id, score1, score2, created_at, winner) VALUES (? ,?, ?, ?, ?, ?)";

    Connection con = DBConnector.connect();
    PreparedStatement stmt = con.prepareStatement(query);

    for (String[] s : fixtures) {

        int winner;
        stmt.setString(1, s[0]);
        stmt.setString(2, s[1]);

        String nullTest1 = s[2];

        if (nullTest1 != null) {
            stmt.setString(3, s[2]);
            stmt.setString(4, s[3]);
            stmt.setString(5, s[4]);
            int score1 = Integer.parseInt(s[2]);
            int score2 = Integer.parseInt(s[3]);
            System.out.println(score1);
            System.out.println(score2);
            if (score1 > score2) {
                winner = 1;
            } else if (score2 > score1) {
                winner = 2;
            } else {
                winner = 0;

            }

            String gameWinner = Integer.toString(winner);
            stmt.setString(6, gameWinner);
        } else {
            System.out.println("empty");
            stmt.setString(3, null);
            stmt.setString(4, null);
            stmt.setString(5, s[4]);
            stmt.setString(6, null);
        }

    }
    stmt.execute();
    stmt.close();
    con.close();
}

InsertFixtures获取列表字符串数组,并使用for循环将它们插入到我的数据库中。 我的问题是:

if(nullTest1 != null ){

当我在调试模式下运行这段代码并将nullTest1设置为等于null时,它跳过这段代码并进入else语句。但是,当我实时运行它时,它会进入这个if语句,并且在parseInt的null值上有一个问题

这是我试图插入数据库的字符串示例:

Fixture 45 42 1 0 1554642300 
Fixture 49 48 null null 0 

任何帮助都是有用的。 谢谢


共 (1) 个答案

  1. # 1 楼答案

    在将String解析为Integer之前,应该检查null

    int score2 = s[3] != null ? Integer.parseInt(s[3]) : 0;
    

    您需要决定s[3] is null的值应该是多少。我把0作为例子