How do I let "bind" to "Sqlitestatement" accept a null value in Sqlite?

Asked

Viewed 187 times

2

I decided to use Sqlitestatement because it is faster to insert data in Sqlite, but at some point a null value can come object.getAlgumthing() and in this case an error with the message that the bind is empty. Does anyone know how to solve this? in the bank I have already created authorized null value in the table.

String sql = "INSERT INTO table (number, nick) VALUES (?, ?)";
SQLiteStatement stmt = db.compileStatement(sql);
for (int i = 0; i < values.size(); i++) {
    stmt.bindString(1, values.get(i).number);
    stmt.bindString(2, values.get(i).nick);
    stmt.execute();
    stmt.clearBindings();
}

*In sql, just do not put the "not null" when creating the tables that the table accepts, but with the bind is giving error before trying to insert in the table.

1 answer

1


It has two forms but both require a prior test to verify that the value is null:

  • Using bindNull()

    String sql = "INSERT INTO table (number, nick) VALUES (?, ?)";
    SQLiteStatement stmt = db.compileStatement(sql);
    for (int i = 0; i < values.size(); i++) {
        if(values.get(i).number == null){
            stmt.bindNull(1);
        }else{
            stmt.bindString(1, values.get(i).number);
        }
        if(values.get(i).nick == null){
            stmt.bindNull(2);
        }else{
            stmt.bindString(2, values.get(i).nick);
        }
        stmt.execute();
        stmt.clearBindings();
    }
    
  • Not do bind for this index, as long as you’ve done it before clearBindings()

    String sql = "INSERT INTO table (number, nick) VALUES (?, ?)";
    SQLiteStatement stmt = db.compileStatement(sql);
    for (int i = 0; i < values.size(); i++) {
        if(values.get(i).number != null){
            stmt.bindString(1, values.get(i).number);
        }
        if(values.get(i).nick != null){
            stmt.bindString(2, values.get(i).nick);
        }
        stmt.execute();
        stmt.clearBindings();
    }
    
  • Yeah, I wanted to avoid doing that check but I’m gonna have to use that. Fight.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.