JDBC: complains about invalid sign but seems fine

前端 未结 3 1485
[愿得一人]
[愿得一人] 2021-01-25 18:41

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

3条回答
  •  忘了有多久
    2021-01-25 19:30

    Are you sure the value of the username variable is 'Jack' and not Jack? (the ORA-00911 error doesn't look like a typical date format error).

    Also you should learn about PreparedStatement. They are more efficient, easier to read and debug and not susceptible to SQL injection.

    My java is a bit rusty, but this would look something like this with a PreparedStatement:

    String query = "insert into user(user_id, username, age, creation_ts) values "
                  + "(seq_userid.NEXTVAL, ?, ?, ?)";
    
    Statement st = conn.prepareStatement(query);
    
    st.setString(1, username);
    st.setInt(2, age);
    st.setTimestamp(3, new java.sql.Timestamp(
                              Calendar.getInstance(
                                 TimeZone.getDefault()).getTimeMillis()));
    
    st.executeUpdate(insertQuery.toString());
    

    This way you don't need to convert a date to a string to get it converted back by the DB. Also you may find the statement easier to read and you will never have to worry about user's naming their account with a ' (single-quote) :)

提交回复
热议问题