简体   繁体   English

如何在mysql中转换字符串类型(java)并存储在日期数据类型中?

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

I want to insert valued from JForm to mysql database.我想从 JForm 插入值到 mysql 数据库。 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 )为了将字符串转换为java.util.Date对象,您需要一个DateFormat (例如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 .使用dateFormat.parse(..)将字符串转换为Date

Since you are using MySQL DB for that you need to Format your s5 variable string to yyyy-mm-dd date.由于您使用的是 MySQL DB,因此您需要将 s5 变量字符串格式化为 yyyy-mm-dd 日期。 You can format it using dateFormat.您可以使用 dateFormat 对其进行格式化。 Or make sure your s5 variable should contain string like this '2000-06-30'或者确保您的 s5 变量应包含这样的字符串 '2000-06-30'

You need to pass a java.util.Date .您需要传递一个java.util.Date You can parse a Date from a String using a SimpleDateFormat .您可以使用SimpleDateFormatString解析Date

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有关您有哪些选项的更多信息,请参阅javadoc
  • 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)作为风格问题,避免使用s1s2等变量名。它们会导致不可读性,从而导致错误:要么使用专有名称,如nameaddress等,要么内联它们(即删除它们并直接使用初始化的代码)他们代替)
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.让我给你一些基本的方法来转换String类型的数据,即我们从网页/HTML页面得到的数据在java中处理,然后插入到Mysql的DB中。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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