简体   繁体   English

如何使用Java将mm-dd-yyyy(来自csv文件中的数据)的格式更改为yyyy-mm-dd存储在MySql中

[英]How to change format of mm-dd-yyyy(of data from csv file) to be stored as yyyy-mm-dd in MySql using Java

The data exists in a csv file. 数据存在于csv文件中。 I am using a CSVReader to read each row and then store the corresponding values in the database. 我正在使用CSVReader读取每一行,然后将相应的值存储在数据库中。 so while reading the strings I split the date string using "-"(date format is like 01-02-1997)and store in an array and then swap the three elements of the array and store it back in the db. 因此,在读取字符串时,我使用“-”(日期格式类似于01-02-1997)分割日期字符串,并将其存储在数组中,然后交换数组的三个元素并将其存储回db中。 Is there any better way. 有没有更好的办法。

Sample Row data in csv file: CSV文件中的示例行数据:

10001   MICHELLE    VILLEGAS3   Savings SRINATH MICHELLE.VILLEGAS3@NOBODY.COM   Y   10-7-18 1050 WEST FIFTH STREET      AZUSA   IND 917023308

it is comma separated only. 它仅以逗号分隔。

private static void readCsv(String tableName) throws FileNotFoundException, IOException, SQLException {
    CSVReader csvreader = null;

    try{
        Reader reader = Files.newBufferedReader(Paths.get(filePath));
        csvreader = new CSVReaderBuilder(reader).withSkipLines(1).build();
        sql = "insert into ? values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
        ManageDBResource.createConnectionToDB();
        pstmt = ManageDBResource.conn.prepareStatement(sql);
        pstmt.setString(1, tableName);

        String[] rowData = null;

        while((rowData = csvreader.readNext()) != null) {

            int i = 2;

            for (String data : rowData) {

                if(i == 8 && data != null && rowData[12] != "IND") {
                    String[] date = data.split("-");
                    String temp = date[0];
                    date[0] = date[1];
                    date[1] = temp;
                }
                pstmt.setString(i++,data);
                //System.out.print(data + " ");
            }
            //System.out.println();
        }
        int result = pstmt.executeUpdate();
        if(result == 1) {
            System.out.println("Data loaded Successfully.");

        }
    }
    finally {
        pstmt.close();
        csvreader.close();
    }

How exactly do I use the STR_TO_DATE() function in the java program. 我到底如何在Java程序中使用STR_TO_DATE()函数。 sorry I am new to programming thanks for helping. 抱歉,我是编程新手,感谢您的帮助。

Why don't you use java's SimpleDateFormat ? 为什么不使用Java的SimpleDateFormat呢?

eg 例如

java.text.SimpleDateFormat source = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = source.parse(data);
java.text.SimpleDateFormat target = new java.text.SimpleDateFormat("yyyy-MM-dd");
data = target.format(date);

or better: The modern java.time API 或更好:现代的java.time API

DateTimeFormatter source = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate date = LocalDate.parse(data, source);
DateTimeFormatter target = DateTimeFormatter.ofPattern("yyyy-MM-dd");
data = date.format(target);

It's quite simple. 这很简单。 Start with this question and convert your column data (String) to java.sql.date . 这个问题开始,并将您的列数据(字符串)转换为java.sql.date Now use setDate method of prepared statement to pass the date to your insert query: 现在,使用prepared语句的setDate方法将日期传递给您的插入查询:

pstmt.setDate(i++, dateObject);

Don't worry about how mysql will store it. 不必担心mysql将如何存储它。 You can always query the DB to get date values in your required format. 您始终可以查询数据库以获取所需格式的日期值。 The tools such as SQL Developer etc. you use can be configured to display date in specific format. 可以将您使用的工具(例如SQL Developer等)配置为以特定格式显示日期。

You can use 您可以使用

final DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate localDate = LocalDate.parse("01-20-2018", dateFormat);
pstmt.setDate(i, java.sql.Date.valueOf(localDate));

If parsing fails the parse method will throw DateTimeParseException . 如果解析失败,则parse方法将引发DateTimeParseException

So you can 所以你可以

LocalDate localDate = null;
try {
     localDate = LocalDate.parse("01-20-2018", dateTimeFormat);
} catch(DateTimeParseException e) {
     e.printStackTrace();
     //some action that should be taken in case it fails
}

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

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