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

查看:203
本文介绍了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());

但是当我运行这样的东西我得到错误:
字符串的语法表示datetime值是不正确的。

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

谢谢

推荐答案

$ c> 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天全站免登陆