Stire JDateChooser日期在数据库中

时间:2016-07-18 23:42:16

标签: java sql date jdatechooser

我想将jDateChooser日期存储在数据库中,其中我有一个sql日期类型的列。这是我使用的代码:

try{ 
        String f_name = qq.getText();
        String l_name= jTextField2.getText();
        String add1 =jTextField4.getText();
        String add2 =jTextField5.getText();
       String add3 =jTextField6.getText();
        String add4 =jComboBox1.getSelectedItem().toString();
        String add= add1+","+add2+","+add3+","+add4+".";
        java.util.Date dob= jDateChooser1.getDate();
        String url="jdbc:sqlserver://localhost:1433;databaseName=gym2 ";
        String username = "mali";
        String password = "12345";
        Connection con =DriverManager.getConnection(url,username,password);
        Statement st = con.createStatement ();

        PreparedStatement pre = con.prepareStatement ("INSERT INTO employee_reg(firstname,lastname,full_address,dateofbirth)VALUES(?,?,?,?)");
        pre.setString(1,f_name);
        pre.setString(2,l_name);
        pre.setString(3,add);
        pre.setDate(4, (Date) dob);
        pre.executeUpdate();

        pre.close();
        con.close();           
    }
    catch(Exception en)   { } 

但它没有用。

1 个答案:

答案 0 :(得分:0)

将util.Date转换为sql.Date而不是转换。见评论:

    try{ 
        String f_name = qq.getText();
        String l_name= jTextField2.getText();
        String add1 =jTextField4.getText();
        String add2 =jTextField5.getText();
        String add3 =jTextField6.getText();
        String add4 =jComboBox1.getSelectedItem().toString();
        String add= add1+","+add2+","+add3+","+add4+".";
        //convert java.uti.Date to java.sql.Date by: 
        java.sql.Date dob= new java.sql.Date(jDateChooser1.getDate().getTime);
        String url="jdbc:sqlserver://localhost:1433;databaseName=gym2 ";
        String username = "mali";
        String password = "12345";
        Connection con =DriverManager.getConnection(url,username,password);
        Statement st = con.createStatement ();

        PreparedStatement pre = con.prepareStatement ("INSERT INTO employee_reg(firstname,lastname,full_address,dateofbirth)VALUES(?,?,?,?)");
        pre.setString(1,f_name);
        pre.setString(2,l_name);
        pre.setString(3,add);
        //no need to cast
        pre.setDate(4, dob);
        pre.executeUpdate();

        pre.close();
        con.close();
    }
    catch(Exception en) {}