简体   繁体   中英

How to convert string type (java) and store in date data type in mysql?

I want to insert valued from JForm to mysql database. But I can't insert values to date field.. This code is working except for date field. Can someone help me..

            String s1=txtUsername.getText();
            String s2=txtPassword.getText();
            String s3=txtName.getText();
            String s4=txtAddress.getText();
            String s5=txtContractEndDetails.getText();


            connection getcon = new connection();
            Connection conn;


    try{
        conn=getcon.creatConnection();

             String sql="insert into TravelGuide(username,password,name,address,contract_end_date)values(?,?,?,?,?)";

             PreparedStatement stmt = conn.prepareStatement(sql);
          java.sql.Date dtValue = java.sql.Date.valueOf(s5); 

           stmt.setString(1, s1);


          stmt.setString(2, s2);

          stmt.setString(3, s3);
           stmt.setString(4, s4);

        stmt.setDate(5, s5);

           stmt.executeUpdate();



        }


    catch(Exception ex){
        JOptionPane.showMessageDialog(PanelTG, ex.getMessage(),"Error Occured 123",2);
    }

In order to turn a string into a java.util.Date object, you need a DateFormat (eg SimpleDateFormat )

  • mask the input field with the desired date format or use a calendar component.
  • use dateFormat.parse(..) to turn the string into a Date .

Since you are using MySQL DB for that you need to Format your s5 variable string to yyyy-mm-dd date. You can format it using dateFormat. Or make sure your s5 variable should contain string like this '2000-06-30'

You need to pass a java.util.Date . You can parse a Date from a String using a SimpleDateFormat .

Your code could look like this:

String s5 = txtContractEndDetails.getText();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date contractEndDate = null;
try {
     contractEndDate = simpleDateFormat.parse(s5);
} catch (ParseException e) {
    // handle telling the user they have bad input
}
stmt.setDate(5, contractEndDate);

Notes:

  • You'll need to chose a date format suitable for your users. See the javadoc for more info on what options you have
  • You need to decide how to handle bad input and code it (either throw an Exception, or show them a message, etc)
  • As a matter of style, avoid variable names like s1 , s2 etc. They lead to unreadability, and thus bugs: Either use proper names like name , address etc, or in-line them (ie remove them and directly use the code that initialized them instead)
public class Test {

    public static void main(String[] args){
        Date date = new Date();

        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String newDate = simpleDateFormat.format(date);
        System.out.println("DateIn String datatype = "+newDate);

        System.out.println("DateIn Date datatype = "+java.sql.Date.valueOf(newDate));

    }
}

Let Me give u basic go throw how to convert String type data ie we got from Web page/HTML page and the data is been processed in java and then insert it into DB of Mysql. Below is just a piece of code.

        String d = req.getParameter("dob");       
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
        java.util.Date convertedDate =  formatter.parse(d);
        java.sql.Date date1 = new java.sql.Date(convertedDate.getTime());
        prestat.setDate(3,  date1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM