aspose file tools*
The moose likes JDBC and the fly likes SQL Dates Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "SQL Dates" Watch "SQL Dates" New topic
Author

SQL Dates

Owen Martin
Greenhorn

Joined: Mar 05, 2010
Posts: 14
Hi there, I am using JDBC and a SQL database.

I have an alarm field in the database which is of date/time.

On my front end I have a String of the format, '01-05-2012' and I am simply inserting it into the database by using the INSERT into X Values ('01-05-2012)

Is this the right way to go about storing a date? Do I need to declare anything the database?
Patryk Sosinski
Greenhorn

Joined: Sep 10, 2011
Posts: 18
Use to_date() function:

create table test (id number primary key, d date);

insert into test values (1, to_date('01-03-2012', 'DD-MM-YYYY'));
Owen Martin
Greenhorn

Joined: Mar 05, 2010
Posts: 14
Get a incorrect syntax error when trying to use to_date, I am using SQL Server and SQL Server Management Studio
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19762
    
  20

I'd prefer to use a PreparedStatement and its setDate method. That's guaranteed to work in all database servers with a JDBC driver:

Alternatively, in MS SQL Server you can use strings to specify the date. You don't want to use "01-05-2012" as the value though, as the server's region determines whether that's January 5th or May 1st. What always works is to use yyyy-MM-dd: "2012-01-05".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Patryk Sosinski
Greenhorn

Joined: Sep 10, 2011
Posts: 18
Ah, sorry. You have to use convert function but i cant write more - dont have MS SQL installed.
Check this out:
http://www.sqlusa.com/bestpractices/datetimeconversion/
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: SQL Dates