0

当我在数据库中运行查询时,以下查询有效

 INSERT INTO `M_DT_SaveAndClose` (`StoryName`, `Assignee`, `Createddate`, `CreatedBy`)
 VALUES (' DT_0019_BGL_2014_11_01_AM_01_MN_01_11_2014_12_07_06_281_000772.xml ',
 ' T0003SathyabamaT ', ' 2014-11-01 12:08:22  ', ' Admin  ')

但是当我使用java通过sql脚本运行相同的查询时,它会抛出错误

"Error executing: INSERT INTO `M_DT_SaveAndClose` (`StoryName`, `Assignee`, `Createddate`, `CreatedBy`) 
   VALUES (' DT_0019_BGL_2014_11_01_AM_01_MN_01_11_2014_12_07_06_281_000772.xml ',
   ' T0003SathyabamaT ', ' 2014-11-01 12:08:22  ', ' Admin  ').
 Cause: net.ucanaccess.jdbc.UcanaccessSQLException: data exception: invalid datetime format"

java中的查询生成步骤:

   savequery = "INSERT INTO `M_DT_SaveAndClose` (`StoryName`, `Assignee`, `Createddate`, `CreatedBy`) VALUES (' " + storyidgen.concat(".xml").trim() + " ', ' " + usernames.trim() + " ', ' " + dateFormat.format(date).trim() + "  ', ' Admin  ');";

访问表结构:

   CREATE TABLE M_DT_SaveAndClose (\n"
            + "  slno Integer,\n"
            + "  StoryName VARCHAR,\n"
            + "  Assignee VARCHAR,\n"
            + "  [Createddate] DateTime,\n"
            + "  CreatedBy VARCHAR,\n"
            + "  [createdtime] DateTime\n"
            + ")

我正在使用 ucanaccess-2.0.6.2.jar。提出一些想法。

4

2 回答 2

1

实际上,正是 [Createddate] 的字符串文字中的前导和尾随空格让您感到困惑。简单地改变

... + " ', ' " + dateFormat.format(date).trim() + " ', ' Admin ' ...

... + " ', '" + dateFormat.format(date).trim() + "', ' Admin ' ...

使错误消失。但是,如果您使用这样的参数化查询,您的代码将更简洁、更易于维护更安全

String savequery = 
        "INSERT INTO M_DT_SaveAndClose (StoryName, Assignee, Createddate, CreatedBy) " +
        "VALUES (?,?,?,?)"; 
try (PreparedStatement ps = conn.prepareStatement(savequery)) {
    ps.setString(1, storyidgen.concat(".xml").trim());
    ps.setString(2, usernames.trim());
    ps.setTimestamp(3, new Timestamp(date.getTime()));
    ps.setString(4, "Admin");
    ps.executeUpdate();
}
于 2014-11-01T09:04:54.893 回答
1

我在您的查询中看到很多看起来可疑的空白。建议你删掉

INSERT INTO `M_DT_SaveAndClose` 
    (`StoryName`, `Assignee`, `Createddate`, `CreatedBy`)
VALUES 
    ('DT_0019_BGL_2014_11_01_AM_01_MN_01_11_2014_12_07_06_281_000772.xml',
     'T0003SathyabamaT', '2014-11-01 12:08:22', 'Admin')
于 2014-11-01T06:55:00.580 回答