1

I have an html string I would like to store in my SQLite db "as is". The special characters in the html string prevent my INSERT statement from storing it:

INSERT INTO myTable VALUES ('" + htmlString + "')

On iOS I used parameterized queries to accomplish this and it worked fine. How can I accomplish this on Android? I've Google parameterized queries for Android but the results were varied and unclear.

1 Answer 1

2

in Android you have parameterized queries too ... are few way to achive this:

ContentValues vals = new ContentValues();
vals.putString("ColumnName", htmlString);
db.insert("myTable", null, vals);

or

final SQLiteStatement insert = db.compileStatement("INSERT INTO myTable VALUES (?)");
insert.bindString(1, htmlString);
//edit: hehe forgot about most important thing 
insert.executeInsert(); 

or

db.rawQuery("INSERT INTO myTable VALUES (?)", new String[] {htmlString});

EDIT: (inserting multiple rows)

if you wana insert more than 1 row then do it in transaction (it should be quicker) and prefer 2nd solution:

db.beginTransaction();
try {
  final SQLiteStatement insert = db.compileStatement("INSERT INTO myTable VALUES (?)");
  for(...){
    insert.clearBindings();
    insert.bindString(1, htmlString[N]);
    //edit: hehe forgot about most important thing 
    insert.executeInsert();
  }
  db.setTransactionSuccessful();
} finally {
  db.endTransaction();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is db.rawQuery the same as db.execSQL just with parameters?? Also, out of the 3 examples you provided, do you favor any one of them over the others?? And if so, why?
execSQL should not be use to SELECT/INSERT/UPDATE/DELETE ... if you need only 1 row then select one of those 3 (really doesn't matter) if you inserting multiple row then see my edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.