当前位置: 代码迷 >> Java Web开发 >> 关于将生日()安插到数据库中出错
  详细解决方案

关于将生日()安插到数据库中出错

热度:100   发布时间:2016-04-16 22:23:54.0
关于将生日()插入到数据库中出错
public void add(Customer c){
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try{
conn = JdbcUtils.getConnection();
String sql = "insert into customer(id,name,gender,birthday,cellphone,email,preference,type,description) values(?,?,?,?,?,?,?,?,?)";
st = conn.prepareStatement(sql);
st.setString(1, c.getId());
st.setString(2, c.getName());
st.setString(3, c.getGender());
st.setDate(4,new java.sql.Date(c.getBirthday().getTime()));
以上是部分代码,在最后一行插入生日时,显示“The method getTime() is undefined for the type String”错误,在网上查好像关于时间的存储就是:new java.sql.Date(date.getTime());我加到里面也是显示没有date类型。请教大神给点意见,该怎么改。。。
------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

Customer birthday是什么类型?


既然是从customer  c里获取,那C里面本身就已经封装了生日,只需get就行,何必还要去new,去gettime

您的意思是直接st.setString(4, c.getBirthday());吗,这样也不行的。


你customer中是String类型,如果你的数据库中生日采用的也是String类型,那就可以直接get、set
如果你的数据库中的生日是Date类型,就需要先将String类型转为Date类型,不确定date类型的话可以先利用new Date()往数据库中插入一条数据,后台查看下数据库中的存储形式,然后同样的形式格式化就行了
------解决方案--------------------
st.setDate(4,new java.sql.Date(new Date(c.getBirthday()).getTime()));

如果不行,请查看new Date构造函数,把你的c.getBirthday()构造成一个Date,在用上面的的方法搞定
------解决方案--------------------
st.setDate(4, new SimpleDateFormat("yyyy-MM-dd").parse(c.getBirthDay());
  相关解决方案