How do I allow "bind" to "SQLiteStatement" to accept a null value in SQLite?

2

I decided to use SQLiteStatement because it is faster to insert data into SQLite, but at some point it may be a null value object.getAlchemistry () and in this case an error with the message that the bind is empty. Does anybody know how to solve this? in the database I have already created a 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 "not null" at the time of creating the tables that the table accepts, but bind is giving error before trying to insert into the table.     

asked by anonymous 10.11.2015 / 19:56

1 answer

1

There are two ways but both require a test that checks to see if 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();
    }
    
  • Do not bind to this index , since you have done 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();
    }
    
11.11.2015 / 14:50