在Eclipse中使用Java的MySQL语法错误

时间:2012-10-31 19:53:54

标签: java mysql sql database

我在Java中为sql编写了以下预备语句:

com.mysql.jdbc.JDBC4PreparedStatement@6e56103e:

INSERT INTO `game` (Id , GameStart ,Name, Lenght, MapVersion, Mode)VALUES(2502591,'2000-03-02 02:02:02','5x5 aptb wdw','00:55:48','DotA v6.75b.w3x','aptb ')ON DUPLICATE KEY UPDATE `Id`=VALUES(Id),`GameStart` = VALUES(GameStart),`Name`=VALUES(Name),`Lenght`=VALUES(Lenght),`MapVersion`=VALUES(MapVersion),`Mode`=VALUES(Mode).

当我在Eclipse中执行它时,我收到以下错误:

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 '?,?,?,?,?,?)ON DUPLICATE KEY UPDATE `Id`=VALUES(Id),`GameStart` = VALUES(GameSta' at line 1.

但是当我在SQLyog中执行相同的查询时,我没有收到错误。行已更新。有什么问题?提前致谢

代码:

  Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dota","root","root");
    PreparedStatement updateGame = null;
    String updatingGame = "INSERT INTO `game` (Id , GameStart ,Name, Lenght, MapVersion, Mode)" +
                "VALUES(?,?,?,?,?,?)" +
                "ON DUPLICATE KEY UPDATE " +
                "`Id`=VALUES(Id),"+
                "`GameStart` = VALUES(GameStart)," +
                "`Name`=VALUES(Name)," +
                "`Lenght`=VALUES(Lenght)," +
                "`MapVersion`=VALUES(MapVersion)," +
                "`Mode`=VALUES(Mode)";
    con.setAutoCommit(false);
    updateGame=con.prepareStatement(updatingGame);
                updateGame.setInt(1, game.Id);
                Timestamp timestamp = new Timestamp(100,2,2,2,2,2,2);
                updateGame.setTimestamp(2,timestamp);
                updateGame.setString(3, game.GameName);
                updateGame.setTime(4, (Time) game.Time);
                updateGame.setString(5, game.MapVersion);
                updateGame.setString(6, game.Mode);
                updateGame.executeUpdate(updatingGame);

然后:

updateGame.executeUpdate(updatingGame);

我收到错误

3 个答案:

答案 0 :(得分:0)

首先,如果你使用的是preparedStatement,你必须这样做

String query="Insert into tablename (col1, col2) values(?,?)";
PreparedStatement stmnt = //get the statement
stmnt.setString(1, "col1val");
stmnt.setString(2, "col2val");

答案 1 :(得分:0)

您正在主键上插入重复值。

按照@ chaitanya10的建议,使用PreparedStatement

您对面向对象的了解程度如何?我可以看到你没有使用正确的封装。

答案 2 :(得分:0)

发现我的错误。我应该只使用executeUpdate()而不是executeUpdate(updatingGame);因为如果我将它与参数一起使用,我将覆盖白化的值

updateGame.setInt(1, game.Id);
Timestamp timestamp = new Timestamp(100,2,2,2,2,2,2);
updateGame.setTimestamp(2,timestamp);
updateGame.setString(3, game.GameName);
updateGame.setTime(4, (Time) game.Time);
updateGame.setString(5, game.MapVersion);
updateGame.setString(6, game.Mode);