1

データが既に存在する場合は更新し、存在しない場合はデータを挿入します。これらのアクションを別々のメソッドに入れる必要がありますか、または 1 回のデータベース呼び出しで実行するオプションはありますか?

public boolean insert_tvShow(TvShow tvShow) {

    java.util.Date myDate = new java.util.Date(tvShow.getReleaseDate());
    boolean success = false;

    try {
        String sqlQuery = "UPDATE tvshows " +
                          "SET title = ?, plot = ?, poster = ?, imdb_rating = ?, imdb_url = ?, imdb_id = ?, release_date = ? WHERE title='?' " +
                          "IF @@ROWCOUNT=0 " +
                          "INSERT INTO tvshows VALUES (title, plot, poster, imdb_rating, imdb_url, imdb_id, release_date) " +
                          "VALUES(?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, tvShow.getTitle()); 
        ps.setString(2, tvShow.getPlot());
        ps.setString(3, tvShow.getPoster());
        ps.setDouble(4, tvShow.getImdb_Rating()); 
        ps.setString(5, tvShow.getImdb_url()); 
        ps.setString(6, tvShow.getImdb_id());
        ps.setDate(7, new java.sql.Date(myDate.getTime()));
        ps.setString(8, tvShow.getTitle());
        ps.setString(9, tvShow.getTitle()); 
        ps.setString(10, tvShow.getPlot());
        ps.setString(11, tvShow.getPoster());
        ps.setDouble(12, tvShow.getImdb_Rating()); 
        ps.setString(13, tvShow.getImdb_url()); 
        ps.setString(14, tvShow.getImdb_id());
        ps.setDate(15, new java.sql.Date(myDate.getTime()));
        ps.executeUpdate();
        success = true;
    } catch(Exception e) {
        //TODO logging
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {}
    }
    return success;
}
4

0 に答える 0