如果数据已经存在,我想更新数据,如果不存在,我想插入数据。我是否必须将这些操作放入单独的方法中,或者是否可以选择在一个数据库调用中执行此操作?
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;
}