使用PreparedStatement将日期插入MySQL数据库 [英] Inserting date into MySQL database using a PreparedStatement

查看:207
本文介绍了使用PreparedStatement将日期插入MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用预准备语句将字符串日期更新到MySQL数据库中。我已经尝试了很多并且始终遇到错误 java.util.Date无法解析为java.sql.Date 或反之亦然。我没有在这里进口任何东西。请根据你的答案导入。

I want to update the string date into MySQL database using prepared statement. I have tried a lot and always got error java.util.Date cannot parse into java.sql.Date or vise versa. I didn't import anything here. Please import according to your answer.

public class Date1 
{ 
    public static void main(String args[]) 
    {
        String source="2008/4/5";              
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");                       
        java.sql.Date d=(Date) format.parse(source);             
        Class.forName("com.mysql.jdbc.Driver");        
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root");   
        PreparedStatement ps=con.prepareStatement("insert into ankur1 values(?)");          
        ps.setDate(1,(java.sql.Date) d);    
        ps.executUpdate();
    }
}


推荐答案

写这个

java.sql.Date d= new java.sql.Date(format.parse(source).getTime());

而不是:

java.sql.Date d=(Date) format.parse(source);

因为你不能只是施放 java.util.Date 到它的子类型 java.sql.Date 。你必须转换它。另请注意,您的格式字符串与您的实际日期格式不符,正如Bill the Lizard所评论的那样。

Because you cannot just cast java.util.Date to its subtype java.sql.Date. You have to convert it. Do also note that your format string doesn't match your actual date format, as Bill the Lizard commented.

这篇关于使用PreparedStatement将日期插入MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆