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

问题描述 投票:-1回答:1

我正在使用预准备语句插入我的数据库。插入的一些值为NULL,因为匹配尚未播放,因此得分为NULL,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语句并且在null值上存在parseInt问题。

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

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

任何帮助都很有用。谢谢

java null prepared-statement
1个回答
1
投票

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

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

如果s[3] is null,你需要决定什么应该是值。我把0仅仅用于举例。

© www.soinside.com 2019 - 2024. All rights reserved.