使用Java在Postgresql中输入Date值

编程入门 行业动态 更新时间:2024-10-28 16:18:21
本文介绍了使用Java在Postgresql中输入Date值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用java& PostgreSQL。我有一些行日期数据类型。但是我不能使用以下代码添加任何条目到数据库中:

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 :

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);

如何在postgreSQL行中添加一个日期,在java中有查询?

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

推荐答案

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

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);

  • 它会抛出一个 NullPointerException 因为你试图取消引用 null
  • 你正在尝试将年份设置为3890AD( java.util.Date 是基于1900年的多年)
  • 然后你将设置月份到6月。如果你以为你把这个月的时间设定到了5月份,那么再考虑一下 - 日期是以0为基础的月份
  • 重新使用已被弃用 - 应该为您提供一个大警戒灯
  • 然后您尝试将 aDate 转换为 java.sql.Date ,但没有迹象表明它是 a java.sql.Date
    • It will throw a NullPointerException because you're trying to dereference null
    • You're then trying to set the year to 3890AD (java.util.Date is 1900-based for years)
    • You're then setting the month to June. If you thought you were setting the month to May, think again - Date is 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 aDate to java.sql.Date but there's no sign that it is a java.sql.Date
    • 我会建议:

      • a href =joda-time.sf =nofollow> Joda Time 作为一个更好的日期/时间API,或 java.util.Calendar
      • 确保在设置值之前实际创建一个实例
      • 可能创建一个新的 java .sql.Date 稍后。
      • Either use Joda Time as 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.Date later on.

      例如:

      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);

更多推荐

使用Java在Postgresql中输入Date值

本文发布于:2023-10-24 05:56:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523107.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   Postgresql   Date

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!