Java 日期 - 插入数据库 [英] Java Date - Insert into database

查看:29
本文介绍了Java 日期 - 插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要想办法将带有 java.util.Date 字段的记录插入到数据库中,但我卡住了.

I need to figure out a way to insert a record with a java.util.Date field into a database and i'm stuck.

有谁知道我该怎么做?现在我有类似的东西.

Does anyone know how i can do this? Right now i have something like.

        java.util.Date myDate = new java.util.Date("01/01/2009");

        sb.append("INSERT INTO USERS");
        sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
        sb.append("VALUES ( ");
        sb.append("  '" + userId + "'");
        sb.append(", '" + myUser.GetFirstname() + "' ");
        sb.append(", '" + myUser.GetLastname() + "' ");
        sb.append(", '" + myUser.GetSex() + "' ");
        sb.append(", '" + myDate  + "'");
        sb.append(")");

        Util.executeUpdate(sb.toString());

但是当我运行这样的东西时,我得到了错误:日期时间值的字符串表示的语法不正确.

But when i run something like this i get the error: The syntax of the string representation of a datetime value is incorrect.

sql 语句如下所示:

Heres what the sql statement looks like:

INSERT INTO USERS (USER_ID
    , FIRST_NAME
    , LAST_NAME
    , SEX
    , CRDATE) 
VALUES (   
    'user'
    , 'FirstTest' 
    , 'LastTest' 
    , 'M'
    , 'Thu Jan 01 00:00:00 CST 2009')

谢谢

推荐答案

当然,PreparedStatement 将使您的代码更好,但要回答您的问题,您需要告诉 DBMS 字符串表示的格式日期的.在 Oracle 中(您不指定数据库供应商),使用 TO_DATE() 函数将字符串日期转换为 Date:

Granted, PreparedStatement will make your code better, but to answer your question you need to tell the DBMS the format of your string representation of the Date. In Oracle (you don't name your database vendor) a string date is converted to Date using the TO_DATE() function:

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('06/06/2006', 'mm/dd/yyyy')
)

这篇关于Java 日期 - 插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆