1

I have a need to use Statement.executeUpdate() to insert data into Database. So every parameter must be embeded into a SQL string. In Database, the type of two columns are datetime: Date1 and Date2 At client side, if I use following statement:

String SQLString = "INSERT INTO Position (" +
    ......
    "Date1, " +
    ......
    "Date2) " +
    "VALUES(" +
    ......
    //"2012-05-29 16:28:58.555" + ", " + // runtime error, always say error at 16
    //"2012-05-29" + ", " + // no runtime error, but lost time and result date is also not correct
    //"10-06-02" + ", " + // no runtime error, but it adds 2 days beginning at 1900-01-01 00:00:00.000
    ......
    null
    ")";

Can anyone tell me how to correctly embedded Datetime into SQL String?

1

2 Answers 2

4

You should use a PreparedStatement and pass the date field ad Date ...

String SQLString = "INSERT INTO Position (Date1) VALUES (?)";
PreparedStatement prest = con.prepareStatement(SQLString);
prest.setDate(1,new Date());
prest.executeUpdate()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply. But I HAVE TO use Statement.executeUpdate(), so Can anyone tell me how to correctly embedded Datetime into SQL String?
What is the SQL version ? Should work with : YYYY-MM-dd HH:mm:ss or without the time simply with : YYYY-MM-dd or YYYYMMdd
2

First up, you have to use PreparedStatement. Then you could do something like:

statement.setDate(2, new Date());

1 Comment

Thank you for your reply. But I HAVE TO use Statement.executeUpdate(), so Can anyone tell me how to correctly embedded Datetime into SQL String?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.