Home > Mobile >  jdbcTemplate query with 5 parameters for insert
jdbcTemplate query with 5 parameters for insert

Time:04-12

I am building a Spring application and in my Repository I have to insert an sql query that has 5 parameters and I tried jdbcTemplate.query or queryForList or Map but it gives me error.

Here is the code:

@Repository
public class BilantErrRepository {
    
    @Autowired
    private DataSource dataSourceMail;
    
    public List<BilantErr> search() {
        
        List<BilantErr> info1 = new ArrayList<>();
        BilantErr bilant = new BilantErr();
        
        JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSourceMail);
        String sql = "INSERT into Aaa (cui,an, data_autorizare,operator,motivatie, tip_perioada) VALUES (?,?,sysdate,?,?,?)";
        info1 = jdbcTemplate.query(sql, bilant.getCui(),bilant.getAn(),bilant.getOperator(),bilant.getOperator(),bilant.getPerioada());
        
        
        return info1;
    }

}

What method can I use to do this insert ? Thanks

CodePudding user response:

this.jdbcTemplate.update( "insert into t_actor (first_name, surname) values (?, ?)", new Object[] {"Leonor", "Watling"});

CodePudding user response:

Try using prepared statement method present for JDBC connection and set values via preparedStatement.setString(index, value) feature.

CodePudding user response:

Use jdbcTemplate.update(String sql, Object... args) method:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    var1, var2
);

or jdbcTemplate.update(String sql, Object[] args, int[] argTypes), if you need to map arguments to SQL types manually:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);
  • Related