日期:2014-05-20  浏览次数:20873 次

sos sos jdbc PreparedStatement 插入datetime类型(数据库 sql server 字段 ddate 是datetime类型)
String ddate = vco.getDdate();//发布日期
jdbcTemplate.update(sql,  
  new PreparedStatementSetter() {  
  public void setValues(PreparedStatement ps) throws SQLException {
  //Date date = null;

  ps.setString(1, cbustype);
  ps.setString(2, "");
  ps.setInt(3, 71);
  ps.setString(4, "");
  ps.setString(5, cdlcode);
  ps.setString(6, "05");
  ps.setString(7, cstcode);
 
  //java.sql.Date date=java.sql.Date.valueOf(ddate);
  //ps.setString(8,"CONVERT(datetime,"+ddate+",103)");  
//ps.setDate(8,(java.sql.Date) ddd);
 

java.util.Date date;
try {
date = (java.util.Date) datef.parse(ddate);
Timestamp tt=new Timestamp(date.getTime());
System.out.println("ddddd"+date);
ps.setTimestamp(8,tt);
} catch (ParseException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
我在页面输入2007-11-12 15:11:0.000 插入的时候提示 从字符串转换为 datetime 时发生语法错误。
 换成这个

java.sql.Date date;
try {
date = (java.sql.Date) datef.parse(ddate);
Timestamp tt=new Timestamp(date.getTime());
System.out.println("ddddd"+date);
ps.setTimestamp(8,tt);
} catch (ParseException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
页面同样输入2007-11-12 15:11:0.000 插入的时候报[action]:java.lang.ClassCastException: java.util.Date
at com.together.sys.service.OperationServiceImpl$3.setValues(OperationServiceImpl.java:410)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:707)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:490)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:703)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:767)
at com.together.sys.service.OperationServiceImpl.insertIvo(OperationServiceImpl.java:390)
at com.together.sys.action.InvcoAction.insert(InvcoAction.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java(Compiled Code))
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java(Compiled Code))
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java(Compiled Code))
at java.lang.reflect.Method.invoke(Method.java(Compiled Code))
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
如何解决  


------解决方案--------------------
stat.setDate() 方法需要java.sql.Date 才可以,java.util.Date 是不行的
你可以这样转一下

Java code
ps.setDate(8,new java.sql.Date(dateUtil.getTime()));

------解决方案--------------------