我如何使用将日期时间值的数组放入准备好的语句中?

问题描述 投票:0回答:1

所以我试图创建一个包含日期和时间的表。我将有多个日期和时间,因此我打算使用数组,但我不知道从Java代码到sql代码的转换如何适用于日期和时间等数据类型。

private static boolean createTable() {
    boolean methodSuccess = false;
    try {
        Database.openConnection();
        String createTable = "CREATE TABLE " + "dateAndTimes" + " ("
                + "event_date DATE NOT NULL, "
                + "start_time TIME(0) NOT NULL, "
                + "end_time TIME(0) NOT NULL)";

        Statement smt = conn.createStatement();
        wasThisMethodSuccessful = smt.execute(createTable);
        Database.closeConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        return methodSuccess;
    }
}



private static boolean addData() {
        boolean methodSuccess = false;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
            Database.openConnection();
            String query = "INSERT INTO " + "dateAndTimes"
                    + " (event_date, start_time, end_time)"
                    + " VALUES (?, ?, ?)";
            PreparedStatement pst = conn.prepareStatement(query);


            LocalDate[] eventDates = {LocalDate.parse("07-JUN-2020")};
            LocalTime[] startTimes = {LocalTime.parse ( "10:00" )};
            LocalTime[] endTimes = {LocalTime.parse ( "17:00" )};


            for (int i = 0; i < eventDates.length; i++) {
                pst.setObject(1, eventDates[i]);
                pst.setObject(2, startTimes[i]);
                pst.setObject(3, endTimes[i]);


                boolean methodSuccess = pst.execute();
            }

            Database.closeConnection();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            return methodSuccess;
        }

    }
java arrays sqlite jdbc
1个回答
0
投票

使用Connection::createArrayOf创建一个数组,然后使用pst将该数组传递到PreparedStatement::setArray

© www.soinside.com 2019 - 2024. All rights reserved.