1

I am trying to run a query using a Data Access Object within a Spring Application but I get a String index out of range error.

This is my DAO

public class UserDao {

   private JdbcTemplate jdbcTemplate;

   public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
       this.jdbcTemplate = jdbcTemplate;
   }

   public int saveUser(User u){
    
     String query = "INSERT INTO `users` VALUES('"+u.getFirstName()+"','"+u.getLastName()+"','"
         +u.getEmail()+"','"+u.getCreatedAt()+"','"+u.getCreatedBy()+"','"+u.getUpdatedAt()+"','"+u.getUpdatedBy()+"')";
 
    return jdbcTemplate.update(query);
  }

}

This is the error enter image description here

This is my Database table structure enter image description here

Even if I substitute the getter methods with actual values I still get the error

4
  • 2
    Are you sure, that you use the correct driver implementation? You tagged question as 'mysql', but in stacktrace I see oracle driver Commented Sep 21, 2020 at 7:03
  • 2
    Does this answer your question? String out of index with SQL developer Commented Sep 21, 2020 at 7:04
  • 4
    A bit of off-topic advice is to use PreparedStatement for building queries, avoid concatenating string yourself for SQL queries. This could lead to SQL Injection attacks. docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html Commented Sep 21, 2020 at 7:28
  • Turns out I was using the wrong DRIVER implementation. I followed this tutorial spring.io/guides/gs/accessing-data-mysql and everything works fine now. Thanks! Commented Sep 21, 2020 at 8:36

1 Answer 1

0

Try using syntax like this:

String.format("INSERT INTO USERS(first_name, last_name, etc...) VALUES(%s, %s, etc...);

It will return a string dynamically created by String.format() method.

Because if you are not defined column names you have to maintain the order in values, and it could be bad because you are missing the id column.

P.S. %d - stands for numbers, %s - stands for strings

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

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.