PreparedStatement pstmt = con.prepareStatement(SQL文のひながた);
pstmt.setInt(パラメータ番号, 数値);
pstmt.setString(パラメータ番号, 文字列);
int r = pstme.executeUpdate();
- 処理結果を判定する
executeUpdateの戻り値で判定
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("ドライバのロードに失敗しました");
}
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:h2:~/mydb", "sa", "");
PreparedStatement pstmt = con.prepareStatement("DELETE FROM MONSTERS WHERE HP <= ? OR NAME = ?");
pstmt.setInt(1, 20);
pstmt.setString(2, "スライム");
int r = pstmt.executeUpdate();
if (r != 0) {
System.out.println(r + "件のモンスターを削除しました");
} else {
System.out.println("該当するモンスターはありませんでした");
}
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}