[英]NumberFormatException because NULL not recognised on prepared statement Java
我正在使用准備好的語句將其插入數據庫。 im插入的某些值是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的問題。
這是im試圖插入我的數據庫中的字符串的示例:
Fixture 45 42 1 0 1554642300
Fixture 49 48 null null 0
任何幫助都是有用的。 謝謝
在將String
解析為Integer
之前,應檢查null
:
int score2 = s[3] != null ? Integer.parseInt(s[3]) : 0;
如果s[3] is null
則需要確定該值s[3] is null
。 我已將0
用作示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.