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

RynohRR
  • 299
  • 5
  • 12
  • 2
    Are you sure, that you use the correct driver implementation? You tagged question as 'mysql', but in stacktrace I see oracle driver – Anton Shelenkov Sep 21 '20 at 07:03
  • 2
    Does this answer your question? [String out of index with SQL developer](https://stackoverflow.com/questions/22031648/string-out-of-index-with-sql-developer) – Sudhir Ojha Sep 21 '20 at 07: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. https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html – miiiii Sep 21 '20 at 07:28
  • Turns out I was using the wrong DRIVER implementation. I followed this tutorial https://spring.io/guides/gs/accessing-data-mysql/ and everything works fine now. Thanks! – RynohRR Sep 21 '20 at 08:36

1 Answers1

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vielen Danke
  • 177
  • 1
  • 6