当我在数据库中运行查询时,以下查询可以正常工作
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。建议一些想法。
答案 0 :(得分: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')
答案 1 :(得分: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();
}