所以我想在数据库中添加一些东西,但它不起作用,它不会做this.statement.executeUpdate(sqlQuery);
。如果我打印出sqlQuery
并在 phpMyAdmin 中调用它,它就可以工作。
我有几个数据库迭代,类似于这个,工作得很好,但是这个随机没有。
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;
}
编辑:
好的,我从现在开始使用 PreparedStatement。但我仍然不会让代码执行。由于我没有错误,我无法知道。可能一个原因是我的 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;
}