使用PreparedStatement将日期插入MySQL数据库

ank*_*iya 4 java jdbc prepared-statement

我想使用预准备语句将字符串日期更新到MySQL数据库中.我已经尝试了很多,总是得到错误java.util.Date cannot parse into java.sql.Date或反之亦然.我这里没有进口任何东西.请根据你的回答导入.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*der 7

写这个

java.sql.Date d= new java.sql.Date(format.parse(source).getTime());
Run Code Online (Sandbox Code Playgroud)

而不是这个:

java.sql.Date d=(Date) format.parse(source);
Run Code Online (Sandbox Code Playgroud)

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