简体   繁体   English

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

[英]How to insert java.util.Date in database?

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.它有效。

Here,这里,

values('"+daterecep+"')

you're basically attempting to store the result of daterecep.toString() in the database.您基本上是在尝试将daterecep.toString()的结果存储在数据库中。 As per the documentation this is in format like as "Sat Jun 6 10:43:00 BOT 2011" (which depends on the locale and timezone.).根据文档,其格式类似于“Sat Jun 6 10:43:00 BOT 2011”(取决于语言环境和时区。)。 The database does not understand it.数据库不理解它。

You should be using PreparedStatement#setTimestamp() to set a DATETIME / TIMESTAMP field 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 DATE field, use setDate() instead.或者当它实际上是一个DATE字段时,请改用setDate()

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

As a bonus, PreparedStatement also saves you from SQL injection attacks .作为奖励, PreparedStatement还可以使您免受SQL 注入攻击

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM