【问题标题】:I cannot update DATETIME in SQL from Java but the insert works fine我无法从 Java 更新 SQL 中的 DATETIME,但插入工作正常
【发布时间】:2016-06-18 04:17:32
【问题描述】:

这是我的代码

java.sql.Timestamp date = 
        new java.sql.Timestamp(new java.util.Date().getTime());

java.text.SimpleDateFormat sdf = 
         new java.text.SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

String currentTime = sdf.format(date)

int abs=0;
Statement tgl = connect.createStatement();
ResultSet rs = tgl.executeQuery("SELECT id_absensi FROM absensi ORDER BY id_absensi DESC LIMIT 1");
   while (rs.next()){
       abs=rs.getInt("id_absensi");
   }
String query = "UPDATE   absensi  SET tgl_keluar ="
        + currentTime
        + " WHERE  'id_absensi'=" + abs ;
Statement aa = connect.createStatement();
int bb = aa.executeUpdate(query);

问题是当我尝试运行它时,我收到了这个通知

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 你有一个 SQL 语法错误;检查与您对应的手册 MariaDB 服务器版本,用于在 '01:59:35 附近使用正确的语法 WHERE 'id_absensi'=1' 在第 1 行

我知道这应该是一个简单的语法错误,但我不知道是哪一个?我什至试图复制实际的mysql语句进行更新 PS。 Select 不是问题,只是更新。

请帮忙

【问题讨论】:

  • 你应该使用preparedStatements 一个...

标签: java mysql jdbc


【解决方案1】:

在 INSERT 查询中,id_absensi 不需要单引号。您还应该使用PreparedStatement 并将Timestamp date 设置为查询参数,如下所示:

String query = "UPDATE absensi SET tgl_keluar=?  WHERE id_absensi=?";
PreparedStatement aa = connect.prepareStatement(query);
aa.setTimestamp(1, date);
aa.setInt(2, abs);
int bb = aa.executeUpdate(query);

【讨论】:

  • 试过了,结果还是一样
  • 你能重新发布你更新的代码和错误信息吗?如果你尝试过,至少你不会看到WHERE 'id_absensi'=1' ,因为id_absensi 周围不应该有单引号
【解决方案2】:

对于更新语句,你应该使用executeUpdate

并提交

【讨论】:

    【解决方案3】:
    String query = "UPDATE absensi SET tgl_keluar = '" + currentTime + "' WHERE 'id_absensi' = " + abs;
    

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2016-01-21
      • 1970-01-01
      • 2017-01-18
      • 2011-06-03
      相关资源
      最近更新 更多