在java中接受日期类型命令行参数

时间:2013-01-12 07:59:35

标签: java date command-line-arguments hsqldb

我正在尝试写这个练习CRUD应用程序。这是一个应用程序来存储与出生日期和时间的联系人。东西。由于我使用命令行来接受输入,&将它存储在HSQLDB数据库中,我不知道如何接受Date类型的参数。我尝试从Sting中解析它很长时间,但它不断抛出SQLDataException

这里是我用于此变量的代码行

//this in the class with main

    private Date dob;

    public Date getDob() {
    return dob;
        }



    public void setDob(Date dob) {
            this.dob = dob;
        }

    System.out.println("Enter date of birth of "+n+" in the format dd/mm/yyyy
    String date = sc2.nextLine();
    long d = Date.parse(date);
    uv.setDob(d);

//class with all the business logic

public void addContact(String cb, String name, long dob, String email, String phno, String tag) {
sql = "insert into "+ cb + "(name,dob,email,phone,tag) values (?,?,?,?,?)";
 try {
    con = JDBCHelper.getConnection();
    ps1 = con.prepareStatement(sql);
    ps1.setString(1, name);
    ps1.setLong(2, dob);
    ps1.setString(3, email);
    ps1.setString(4,phno);
    ps1.setString(5, tag);
 }   
 catch(SQLException e) {
    e.printStackTrace();
 }

}

例外,它让我输入日期

java.sql.SQLSyntaxErrorException: incompatible data type in conversion
        at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.Util.throwError(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.setParameter(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.setLongParameter(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.setLong(Unknown Source)
Caused by: org.hsqldb.HsqlException: incompatible data type in conversion
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.types.DateTimeType.convertJavaToSQL(Unknown Source)

4 个答案:

答案 0 :(得分:1)

您必须创建sql Date。构造函数需要很长时间,所以你应该没问题。

ps1.setDate(2, new java.sql.Date(dob));

答案 1 :(得分:0)

要解析字符串到目前为止,您可以使用类SimpleDateFormat,例如:

SimpleDateFormat simpleDateFormat =
        new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
Date date = simpleDateFormat.parse(date);

然后您可以使用PreparedStatementsetDate(int, Date)方法。

答案 2 :(得分:0)

使用SimpleDateFormat作为第一步解析日期,并确保输入采用您想要的格式。然后,您可以在预准备语句中使用相同的值。

Also, try this

答案 3 :(得分:0)

对于任意日期格式,使用SimpleDateFormat获取java.util.Date,然后将其转换为JDBC日期:java.sql.Date sqlDate = new java.sql.Date(date.getTime()))。对于SQL兼容格式(yyyy-MM-dd),有java.sql.Date.valueOf(String)个助手。

相关问题