Search code examples
javaoracle-databasejdbcoracle11gora-00911

JDBC: complains about invalid sign but seems fine


I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception. But when I perform the query in squirrel it gets commited just fine. Does anyone know why this is happening?


Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
        {       
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
            String url = "privatized";
            Connection conn = DriverManager.getConnection(url, "username", "password");

            Statement st = conn.createStatement();

            Format formatter = new SimpleDateFormat(dateTimeFormatString);
            String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime()); 

            StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
                insertQuery.append(username);
                insertQuery.append(",");
            insertQuery.append(age);
            insertQuery.append(",TO_TIMESTAMP('");
            insertQuery.append(formattedDate);
            insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
            System.err.println(insertQuery.toString());
            st.executeUpdate(insertQuery.toString());

            conn.close();
        } catch (SQLException ex){
            System.err.println(ex.getMessage());
            System.err.println(ex.getCause().toString());
            ex.printStackTrace();
            System.out.println("=========================================");
        } catch(Exception ex) {
            System.err.println(ex.getMessage());
        }

Solution

  • As I put in a comment above, the issue could be due to the extra Semicolon at the end of your SQL statement. see this article

    You may also want to look at PreparedStatments to make your life easier. Here would be a rough translation of your above code. I have left some parts, and there are most likely errors.

    String query = "insert into user(user_id, username, age, creation_ts) values(?,?,?,?)";
    PreparedStatement pstmt = conn.prepareStatement(query);
    ... //fill in all your parameters
    pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()) );
    ... //execute here