繁体   English   中英

字符串到 java.sql.Date

[英]String to java.sql.Date

我意识到这已经被问了很多。 我确实看过。 我花了几个小时环顾四周并试图弄清楚这一点。 我应该制作一个程序,在数据库中存储相当于约会列表的内容,包括描述、日期、开始时间和结束时间。 它必须接受用户的输入才能添加或取消约会,因此据我所知,这意味着我需要将字符串转换为日期。

这些是我的导入: import java.io.File; 导入 java.io.IOException; 导入 java.sql.Connection; 导入 java.sql.Date; 导入 java.sql.PreparedStatement; 导入 java.sql.ResultSet; 导入 java.sql.ResultSetMetaData; 导入 java.sql.SQLException; 导入 java.sql.Time; 导入 java.text.DateFormat; 导入 java.text.ParseException; 导入 java.text.SimpleDateFormat; 导入 java.util.ArrayList; 导入 java.util.Scanner;

如您所见,那里没有 java.util.Date。 这是我收到错误的地方:

private static java.sql.Date getDay()
{
    Scanner in = new Scanner(System.in);
    String input;
    Date apptDay = null;
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    java.sql.Date sqlDate;
    System.out.println("\nPlease enter the date of the appointment, format: yyyy/mm/dd");
    while(apptDay == null)
    {
        try
        {
            input = in.next();
            apptDay = (Date) df.parse(input);
        }
        catch(ParseException e)
        {
            System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
        }
    }
    sqlDate = new Date(apptDay.getTime());
    return sqlDate;
}

我已经向它添加了 java.sql.Dates 并试图让它工作,但它仍然给我这个:

Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date at Calendar.getDay(Calendar.java:47)

任何关于我做错了什么或如何使这项工作的想法都将不胜感激。

编辑:我想如果我添加调用它的代码可能会有所帮助,所以也许它会更清楚我如何尝试使用它,所以这里是 addAppointment() 方法,所以你可以看到 getDay( ) 正在被调用以及它要去哪里。

public static void addAppointment() throws SQLException
{
    //get the info
    String desc = getDesc();
    java.sql.Date apptDay = getDay();
    Time[] times = getTime();
    Time startTime = times[0];
    Time endTime = times[1];
    int key;

    Connection conn = SimpleDataSource.getConnection(); //connect to the database

    try
    {
        PreparedStatement max = conn.prepareStatement("SELECT MAX(ID) FROM Calendar");
        ResultSet result = max.executeQuery();
        key = result.getInt("ID") + 1; 
        PreparedStatement stat = conn.prepareStatement(
                "INSERT INTO Calendar " +
                "VALUES (?, ?, ?, ?, ?)"); 
        stat.setInt(1, key);
        stat.setString(2, desc); 
        stat.setDate(3, apptDay);
        stat.setTime(4, startTime);
        stat.setTime(5, endTime);
        stat.execute();
        System.out.println("\nAppointment added!\n");
    }
    finally
    {
        conn.close(); //finished with the database
    }
}

将输入格式更改为yyyy-MM-dd并使用java.sql.Date.valueOf(String date)方法将上述格式的字符串直接转换为 java.sql.Date 值会简单得多。

这应该有效:

private static java.sql.Date getDay()
{
    Scanner in = new Scanner(System.in);
    String input;
    Date apptDay = null;
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    java.sql.Date sqlDate;
    System.out.println("\nPlease enter the date of the appointment, format: yyyy/mm/dd");
    while(apptDay == null)
    {
        try
        {
            input = in.next();
            apptDay = (Date) df.parse(input);
        }
        catch(ParseException e)
        {
            System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
        }
    }
    sqlDate = new java.sql.Date(apptDay.getTime());
    return sqlDate;
}

java.sql.Datejava.util.Date是两个不同的类。 您需要将 sql 日期转换为与 Calendar 兼容的 util 日期。

  Date jDate =  new Date(sqlDate.getTime());

反之亦然

  java.sql.Date sqlDate =  new java.sql.Date(jDate.getTime());

以下语句导致错误:

apptDay = (java.sql.Date) df.parse(input);

实际上, java.text.DateFormat.parse(String)的返回值类型是java.util.Date ,是java.sql.Date无法比拟的。

在您的情况下,最简单的方法可能是使用java.util.Date而不是java.sql.Date

另一个注意事项:您的类名Calendarjava.util.Calendar重复。 使用标准库已经使用的类名并不是一种好的编码风格。

   sqlDate = new java.sql.Date(apptDay.getTime());
Date.valueOf(scanner.nextLine())
String strDate = scanner.nextLine();

SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = format.parse(strDate);

试试下面的方法 -

private static java.sql.Date getDay() throws SQLException {
    Scanner in = new Scanner(System.in);
    String input;
    java.util.Date utilDay = null;
    DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
    System.out.println("\nPlease enter the date of the appointment, format: yyyy-mm-dd");
    while(utilDay == null){
        try{
            input = in.next();
            utilDay = (java.util.Date) df.parse(input);
        }catch(ParseException e){
            System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
        }
   }

   java.sql.Date sqlDate = new java.sql.Date(utilDay.getTime());
   return sqlDate;
}

main()方法中,调用此方法 -

Date birthday = getDay();

时间

是时候有人写下这个问题的现代答案了。

假设您正在使用(或可以开始使用)符合 JDBC 4.2 的驱动程序,则不应使用两个Date类,也不应使用DateFormatSimpleDateFormat 所有这些类都设计得很差,最后两个特别麻烦。 它们也早已过时。 而是依赖 java.time,现代 Java 日期和时间 API。 和它一起工作要好得多。 我们需要一个LocalDate和一个DateTimeFormatter

现在我们开始了,也不要使用java.sql.Time 使用LocalTime从java.time。

所以你的变量声明变成了:

    //get the info
    String desc = getDesc();
    LocalDate apptDay = getDay();
    LocalTime[] times = getTime();
    LocalTime startTime = times[0];
    LocalTime endTime = times[1];
    int key;

仅用于将 java.time 对象传递给准备好的语句,您不使用setDatesetTime 您需要使用setObject

        stat.setInt(1, key);
        stat.setString(2, desc); 
        stat.setObject(3, apptDay);
        stat.setObject(4, startTime);
        stat.setObject(5, endTime);
        stat.execute();

其他一切都和以前一样。 为了将用户输入字符串解析为LocalDate ,这里有一个简短的演示:

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/M/d");
    String input = "2019/11/09";
    try {
        LocalDate aptDate = LocalDate.parse(input, dateFormatter);
        System.out.println("Parsed date: " + aptDate);
    } catch (DateTimeParseException dtpe) {
        System.out.println("Please enter a valid date. Format is yyyy/mm/dd");
    }

最后一个片段的输出是:

解析日期:2019-11-09

我在格式模式字符串中只指定了一个M和一个d以允许用户输入一或两位数字表示月份和月份的日期,例如2019/11/9 我认识的大多数用户都会欣赏这一点。

关联

暂无
暂无

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

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