Frage

I'm using JDBI to insert some data to a mysql table with an auto increment Primary Key. I used indexes to do the insert. The code looks like this:

public void insertWorkout(String[] values) {
    String insertString = "insert into workouts(<column_names>) values(:0,:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16,:17,:18,:19,:20,:21,:22,:23,:24,:25,:26,:27,:28,:29,:30,:31)";
    Update pUpdate = handle.createStatement(insertString);

    for(int i=0; i<vals.length;i++) {
        pUpdate.bind(i, vals[i]);
    }

    pUpdate.execute();
}

This has been working fine for awhile because values[] was always the correct count(32) and the arguments were always in the same order. Now though it's going to have to deal with being passed a smaller array(18,19, or 20) and still do the insert correctly; the last 14 or so args can be empty or blank. The order of the values is still static(ie if passed 18 columns it's the first 18 columns in the table) and and the last 20 columns are all int(11) columns.

Right now when it's passed a smaller than 32 array it gives an error like this:

org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException: Unable to execute, no named parameter matches "20" and no positional param for place 20 (which is 21 in the JDBC 'start at 1' scheme) has been set. 

What is the best way to solve this?

War es hilfreich?

Lösung

As long as the column ordering is static and the missing columns are all int types in the DB, you should be able to just bind a null for each remaining missing argument. Something like this should work:

String insertString = "insert into workouts....."
Update pUpdate = handle.createStatement(insertString);

for(int i=0; i<vals.length;i++) {
        pUpdate.bind(i, vals[i]);
}

if (values.length < 32) {
    for(int i =(32 - values.length); i<32;i++) {
        pUpdate.bindNull(i, java.sql.Types.INTEGER);
    }
}

pUpdate.execute();

That said it might be best to bind each argument by name instead of using an index.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top