PreparedStatement未正确执行

时间:2013-04-14 04:06:10

标签: java mysql prepared-statement

query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= !;";
     query = query.replace("?", "'"+post.getDatetime()+"'");
     query = query.replace("!", Integer.toString(post.getPublisher().getID()));

    PreparedStatement pstm = con.prepareStatement(query);
    ResultSet rs = pstm.executeQuery();

生成的查询如下所示

SELECT * FROM POST_COMMENT WHERE Post_date_time= '2013-04-12 07:20:34.0' AND Post_User= 378;

哪个在MySQL提示行中正常工作,但是从预准备语句启动时会抛出此错误:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '07:20:34.0 AND Post_User=378' at line 1

但是

pstm.setString(1, post.getDatetime());
pstm.setString(2, Integer.toString(post.getPublisher().getID()));

也不起作用。

表格定义

CREATE TABLE Post_Comment (
  Comment_ID INTEGER(7) NOT NULL,
  Post_date_time DATETIME NOT NULL,
  Post_User INTEGER(7) NOT NULL,
  PRIMARY KEY(Comment_ID, Post_date_time, Post_User),
  CONSTRAINT Post_Comment_Post
    FOREIGN KEY (Post_User, Post_date_time)
    REFERENCES Post (User, date_time)
    ON DELETE   CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT Post_Comment_Comment
    FOREIGN KEY (Comment_ID)
    REFERENCES Commentary (ID)
    ON DELETE   CASCADE
    ON UPDATE CASCADE
)
;

请帮忙。

2 个答案:

答案 0 :(得分:3)

query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= ?;";

PreparedStatement pstm = con.prepareStatement(query);
pstm.setObject(1, post.getDatetime());
pstm.setObject(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();

答案 1 :(得分:3)

看看the Java tutorials。你不应该使用String函数replace()字段。

你应该拨打"set" methods of the PreparedStatement


编辑:

不,看看可用的方法。以及数据库列期望的类型。如果您想要日期,请使用setDate(),如果您需要整数,请使用setInt()。例如:

query = "SELECT * FROM POST_COMMENT WHERE Post_date_time = ? AND Post_User = ?;";

PreparedStatement pstm = con.prepareStatement(query);
pstm.setDate(1, post.getDatetime());
pstm.setInt(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();

另请注意,查询使用? 两个占位符,而不是!