tags:

views:

38

answers:

4

Hello All,

I am having a textbox field in my jsp called "req_date". The user is selecting a date from a javascript calendar in the format of "DD-MON-YY" ex. "29-aug-2010".So, now I am stuck while trying to insert it in the DB.

I tried " String queryString = "INSERT INTO Charity (req_date) VALUES (?)", but it is not inserting. How do I solve tis out.

The req_date is type of date in the DB.

Can you please help

+1  A: 

Date format depends upon Database you use. For reference Date formats with Oracle.

so your query should look like :

String queryString = "INSERT INTO Charity (req_date) VALUES (to_date('29-aug-2010', 'dd-mon-yyyy'))"

This is just to answer your question. But I will prefer usage of PreparedStatement as also suggested in other answers.

Your code using PreparedStatement should look something like following: (NOTE: I have not tested this code )

    String formatIn = "dd-MMM-yyyy";
    SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
    java.util.Date inDate = sdfi.parse("29-Aug-2010");

    java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());

    PreparedStatement prest = con
            .prepareStatement("INSERT INTO Charity (req_date) VALUES (?)");
    prest.setDate(1, sqlDate);
    int row = prest.executeUpdate();
YoK
certainly not.. format is presentation responsibility.
Bozho
How to do that in my previous stetement?
maas
@maas I have updated your query using to_date() oracle function.
YoK
Thank you YOK, it worked
maas
I have also added solution using preparedStatement. Please have a look
YoK
now that deserves a +1 :)
Bozho
A: 

It depends on your database, PostgreSQL does recognize this format:

SELECT CAST('29-aug-2010' AS date);

Result:

'2010-08-29'

In most cases, you'd better use the ISO-format yyyy-mm-dd.

Frank Heikens
How to change the format in the insert?
maas
Depends, you could use TO_DATE() in SQL as YoK showed you or do it in your Java-code.
Frank Heikens
+3  A: 

Use a PreparedStatement and its setDate(..). Or use a timestamp (long).

Bozho
Simple one Bozho :)
org.life.java