Search code examples
javajdbcprepared-statementmssql-jdbcsql-timestamp

Prepared statement using Timestamp needs more nanoseconds


I am using the following statement to obtain a timestamp from my SQL DB:

stmt.setTimestamp(i++, new java.sql.Timestamp(example.getExampleDate().getTime()))

Which works just fine and returns:

2013-02-22 12:27:34.0 

Now it happens that I need it to be more precise, like this:

2013-02-22 12:27:34.000

So I found the following method in the docs which apparently is exactly what I want:

setNanos(int n)

Sets this Timestamp object's nanos field to the given value.

But I need to figure out how to include that into my prepared statement?

I tried for example

stmt.setTimestamp(i++, new java.sql.Timestamp(example.getExampleDate().getTime()).setNanos(3));

but than that returns the following error:

The method setTimestamp(int, Timestamp) in the type PreparedStatement is not applicable for the arguments (int, void)

Thanks alot for your help!


Solution

  • setNanos() returns void. So the expression new java.sql.Timestamp(example.getExampleDate().getTime()).setNanos(3) is of type void. You can't pass a void to the method setTimestamp(). You must pass a Timestamp.

    So use a variable:

    Timestamp timestamp = new Timestamp(example.getExampleDate().getTime());
    timestamp.setNanos(3);
    stmt.setTimestamp(i++, timestamp);