【问题标题】:How to embeded Datetime into SQL String如何将日期时间嵌入 SQL 字符串
【发布时间】:2012-05-29 15:15:25
【问题描述】:

我需要使用Statement.executeUpdate() 将数据插入数据库。 因此,每个参数都必须嵌入到 SQL 字符串中。 在数据库中,两列的类型是日期时间:Date1 和 Date2 在客户端,如果我使用以下语句:

String SQLString = "INSERT INTO Position (" +
    ......
    "Date1, " +
    ......
    "Date2) " +
    "VALUES(" +
    ......
    //"2012-05-29 16:28:58.555" + ", " + // runtime error, always say error at 16
    //"2012-05-29" + ", " + // no runtime error, but lost time and result date is also not correct
    //"10-06-02" + ", " + // no runtime error, but it adds 2 days beginning at 1900-01-01 00:00:00.000
    ......
    null
    ")";

谁能告诉我如何正确地将日期时间嵌入到 SQL 字符串中?

【问题讨论】:

标签: java sql datetime


【解决方案1】:

您应该使用PreparedStatement 并传递日期字段广告Date ...

String SQLString = "INSERT INTO Position (Date1) VALUES (?)";
PreparedStatement prest = con.prepareStatement(SQLString);
prest.setDate(1,new Date());
prest.executeUpdate()

【讨论】:

  • 感谢您的回复。但是我必须使用 Statement.executeUpdate(),所以谁能告诉我如何正确地将 Datetime 嵌入到 SQL 字符串中?
  • 什么是 SQL 版本?应该与 : YYYY-MM-dd HH:mm:ss 一起使用,或者没有时间只需使用 : YYYY-MM-dd 或 YYYYMMdd
【解决方案2】:

首先,您必须使用PreparedStatement。然后你可以这样做:

statement.setDate(2, new Date());

【讨论】:

  • 感谢您的回复。但是我必须使用 Statement.executeUpdate(),所以谁能告诉我如何正确地将 Datetime 嵌入到 SQL 字符串中?
猜你喜欢
  • 2019-04-12
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
相关资源
最近更新 更多