使用 Java 在 Postgresql 中输入日期值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7662617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:20:45  来源:igfitidea点击:

Entering a Date value in Postgresql with Java

javapostgresqldatejdbc

提问by Zzap

I am trying to program a database application with java & PostgreSQL. I have some rows with date data type. But i cant add any entries to the database with this code :

我正在尝试使用 java 和 PostgreSQL 编写数据库应用程序。我有一些日期数据类型的行。但我无法使用此代码向数据库添加任何条目:

Date aDate = null;
aDate.setYear(1990);
aDate.setDate(01);
aDate.setMonth(05);

preparedStatement prep = connection.prepareStatement("insert 
into exampletable values (?,?);");
prep.setDate(1, (java.sql.Date) aDate);
prep.setDate(2, (java.sql.Date) aDate);

How can i add a date in a postgreSQL row with queries in java?

如何使用 java 中的查询在 postgreSQL 行中添加日期?

回答by Jon Skeet

It's not clear whether or not this is your only problem, but this code is almost certainly not what you want:

目前尚不清楚这是否是您唯一的问题,但这段代码几乎肯定不是您想要的:

Date aDate = null;
aDate.setYear(1990);
aDate.setDate(01);
aDate.setMonth(05);
  • It will throw a NullPointerExceptionbecause you're trying to dereference null
  • You're then trying to set the year to 3890AD (java.util.Dateis 1900-based for years)
  • You're then setting the month to June. If you thought you were setting the month to May, think again - Dateis 0-based for months
  • All the methods you're using are deprecated - that should raise a big warning light for you
  • You're then trying to cast aDateto java.sql.Datebut there's no sign that it isa java.sql.Date
  • 它会抛出一个NullPointerException因为你试图取消引用null
  • 然后,您尝试将年份设置为 3890AD(java.util.Date多年来以 1900 为基础)
  • 然后您将月份设置为六月。如果您认为您将月份设置为五月,请再想一想 -Date几个月为 0 为基础
  • 您使用的所有方法都已弃用 - 这应该为您发出警告
  • 那么你想投aDatejava.sql.Date,但没有迹象表明它一个java.sql.Date

I would suggest:

我会建议:

  • Either use Joda Timeas a far better date/time API, or java.util.Calendar
  • Make sure you actually create an instance before you set values
  • Probably create a new java.sql.Datelater on.
  • 要么使用Joda Time作为更好的日期/时间 API,要么java.util.Calendar
  • 确保在设置值之前实际创建了一个实例
  • 以后可能会创建一个新的java.sql.Date

For example:

例如:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1990);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, 4); // Assuming you wanted May 1st

java.sql.Date date = new java.sql.Date(calendar.getTime().getTime());

// Ideally specify the columns here as well...
PreparedStatement prep = connection.prepareStatement(
    "insert into exampletable values (?,?)");
prep.setDate(1, date);
prep.setDate(2, date);