创建一个新列,其中包含从用户和日期列中获取的日期差异

时间:2014-07-13 07:33:42

标签: java sql

我正在尝试使用no创建一个列。用户给定日期和使用访问数据库在java中的表的列中存储的日期之间的天数。这是我的代码。我是一名新开发人员,在这方面没有多少经验。所以,如果您发现我的代码有任何问题,请告诉我。

import    java.sql.Connection;
import    java.sql.DriverManager;
import    java.sql.Statement;
import    java.util.*;
import    java.text.*;

public    class DBTest {
public    static void main(String[] args)  {
// my code to accept a date from user
Scanner sc = new Scanner(System.in); 
System.out.print("Enter Date: "); 
String ind = sc.nextLine();
DateFormat df = new SimpleDateFormat("dd.mm.yyyy");
Date d = null; 
try {

d=df.parse(ind);

}
catch(ParseException e) {
System.out.println("Unable to parse " + ind);}


DateFormat df3 = new SimpleDateFormat("dd.mm.yyyy");


String s3 = df3.format(d);


System.out.println("The entered date is: " + s3);

//my code to use that date and subtract a column of dates from it to get the difference   in days.

try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:odbc:dbconnect");
    Statement s = conn.createStatement();

    String tablename = "datetable17";
    String createTable = "CREATE TABLE " + tablename + " AS SELECT DATEDIFF(day, " + s3             + ",SELECT EntryDate FROM MaterialsAging)) AS DiffDate";
    s.execute(createTable);     
    s.close();
    conn.close();
}
catch(Exception ex)
{
    ex.printStackTrace();
}
}
}

1 个答案:

答案 0 :(得分:0)

使用DateDiff函数的代码应如下所示: DATEDIFF( 'd',的ColumnName,GivenDate) 'd'是天。如果你想要几个月的差异然后你应该查找符号,可能是'm'。我相信它也可以做几周和类似的事情。

由于您的GivenDate不是来自数据库中的其他字段,您可能必须给它'撇号'

这将为您提供计算GivenDate - ColumnName =天数。 希望有所帮助。我自己也是新手,通过大量的试验和错误(以及一些stackoverflow帮助)学到了这些东西。

我还听说JDBC-ODBC驱动程序有问题,java 8不支持,因此请优先更改驱动程序Asap。我已经为我自己的java-MSAccess软件推荐了Jackcess和UCanAccess