だから私はデータベースに何かを追加したいのですが、うまくいきませんthis.statement.executeUpdate(sqlQuery);
。を印刷してsqlQuery
phpMyAdmin で呼び出すと、機能します。
これに似たいくつかのDB反復があり、完全に正常に機能していますが、これはランダムに機能しません。
SQL クエリ:
INSERT INTO tvshows (title, plot, poster, imdb_rating, imdb_url, imdb_id, release_date)
VALUES('The Office', 'A mockumentary on a group of typical office workers, where the workday consists of ego clashes, inappropriate behavior, and tedium. Based on the hit BBC series.', 'http://ia.media-imdb.com/images/M/MV5BMTgzNjAzMDE0NF5BMl5BanBnXkFtZTcwNTEyMzM3OA@@._V1._SY317_CR9,0,214,317_.jpg', '8.9', 'http://www.imdb.com/title/tt0386676/', 'tt0386676', '2005-06-11')
コード:
public boolean insert_tvShow(TvShow tvShow) {
boolean success = false;
String plot = tvShow.getPlot();
plot = plot.replaceAll("'", "''");
try {
this.statement = this.connection.createStatement();
String sqlQuery = String.format("INSERT INTO tvshows (title, plot, poster, imdb_rating, imdb_url, imdb_id, release_date) " +
"VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
tvShow.getTitle(),
plot,
tvShow.getPoster(),
tvShow.getImdb_Rating(),
tvShow.getImdb_url(),
tvShow.getImdb_id(),
tvShow.getReleaseDate());
System.out.println(sqlQuery);
this.statement.executeUpdate(sqlQuery);
success = true;
} catch(Exception e) {
} finally {
try {
connection.close();
} catch (SQLException e) {}
}
return success;
}
編集:
OK、これからは PreparedStatement を使用します。しかし、まだコードを実行できません。エラーが発生しないため、知る方法がありません。おそらく 1 つの原因は私の release_date であるため、最初はそれなしで機能するようにします。"ps.executeUpdate();" コードが到達する場所です。
public boolean insert_tvShow(TvShow tvShow) {
boolean success = false;
java.util.Date myDate = new java.util.Date("10/10/2009");
try {
String sqlString = "INSERT INTO tvshows (title, plot, poster, imdb_rating, imdb_url, imdb_id, release_date) " +
"VALUES(?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(sqlString);
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.executeUpdate();
connection.commit();
success = true;
} catch(Exception e) {
//TODO logging
} finally {
try {
connection.close();
} catch (SQLException e) {}
}
return success;
}