0

I have this table in SQL Oracle database

MESSAGES
--------
Name           Null?    Type           
-------------- -------- -------------- 
ID_MESSAGE      NOT NULL NUMBER(38)     
CONTENT          NOT NULL NVARCHAR2(500) 
TIME_STAMP NOT NULL TIMESTAMP(6)  

And I'm trying to insert a data into this table but I'm having a problem with inserting a timestamp.

I've generated a timestamp in Java and executed the following query:

Timestamp timeStamp = new Timestamp(System.currentTimeMillis());


String query = "INSERT INTO messages(content, time_stamp) VALUES ('"+textAreaSendMessage.getText()+"', "+timeStamp+")";

st.executeQuery(query);

And I'm getting this error:

Caused by: java.sql.SQLSyntaxErrorException: ORA-00917: missing comma

How to fix this so it inserts timestamp into a database?

1
  • 3
    Use parameters with types. Don't munge query strings. Commented May 4, 2019 at 15:20

2 Answers 2

2

Use DEFAULT when defining your table to call a function that captures the current moment. This function will automatically run every time you INSERT a new row. Then no need for any Java for this purpose.

If you do want to do something like this in Java, do not use java.time.Timestamp. That class was supplanted years ago by the java.time classes.

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

Build your SQL string using ? placeholders. Do not wrangle with string manipulations as seen in your code sample.

Pass the OffsetDateTime object to fill in for the ? placeholder using a PreparedStatement object.

myPreparedStatement.setObject( … , odt ) ;

Table of date-time types in Java (both modern and legacy) and in standard SQL.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your recommendation. I will make sure to change all statements in the code to this format as it's more clear in the code and I don't have to search for ' character every single time I am trying to insert something as a String.
0

I found out that I don't even have to create timestamp in java, just add CURRENT_TIMESTAMP to the place of timestamp into the query where Timestamp should be.

Comments

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.