如何在数据库中插入 java.util.Date?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6237276/
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-30 14:58:11  来源:igfitidea点击:

How to insert java.util.Date in database?

javajdbc

提问by hibara

I want to insert a date in the database, but it does not work any error message that appears. When I look at my table in Oracle DB I can not find my data that I inserted.

我想在数据库中插入一个日期,但它不起作用任何出现的错误消息。当我在 Oracle DB 中查看我的表时,我找不到我插入的数据。

java.util.Date daterecep;
// getter and setter
public void setdaterecep( java.util.Date daterecep) {
         this.daterecep=daterecep;
} 
public  java.util.Date getdaterecep() {
       return  daterecep;
}

and

    nt val=0;
    try {
        val = st.executeUpdate("insert into tabdate (date) values('"+daterecep+"')" );
    } catch (SQLException ex) {
         Logger.getLogger(Insertdate.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(val);
    return resultat;
}

I used PreparedStatement but it did not worked I just tried to execute the Java code

我使用了 PreparedStatement 但它没有用我只是尝试执行 Java 代码

val = st.executeUpdate("insert into tabdate(date) values('12/12/2004')");

and add

并添加

public static void main (String args[]) throws SQLException {

    Insertdate B= new Insertdate();
    B.connexionBD();
    B.insert();//function for the insertion
}

and it works.

它有效。

回答by BalusC

Here,

这里,

values('"+daterecep+"')

you're basically attempting to store the result of daterecep.toString()in the database. As per the documentationthis is in format like as "Sat Jun 6 10:43:00 BOT 2011" (which depends on the locale and timezone!). The database does not understand it.

您基本上是在尝试将 的结果存储daterecep.toString()在数据库中。根据文档,其格式类似于“Sat Jun 6 10:43:00 BOT 2011”(取决于语言环境和时区!)。数据库不理解它。

You should be using PreparedStatement#setTimestamp()to set a DATETIME/TIMESTAMPfield in a DB.

您应该使用在数据库中PreparedStatement#setTimestamp()设置DATETIME/TIMESTAMP字段。

preparedStatement = connection.prepareStatement("insert into tabdate (date) values(?)" );
preparedStatement.setTimestamp(1, new Timestamp(daterecep.getTime()));
preparedStatement.executeUpdate();

Or when it's actually a DATEfield, use setDate()instead.

或者当它实际上是一个DATE字段时,请setDate()改用。

preparedStatement.setDate(1, new java.sql.Date(daterecep.getTime()));

As a bonus, PreparedStatementalso saves you from SQL injection attacks.

作为奖励,PreparedStatement还可以避免SQL 注入攻击

See also:

也可以看看: