SQLite - Is it possible to insert a BLOB via insert statement?

前端 未结 2 1685
失恋的感觉
失恋的感觉 2021-01-04 03:51

I\'m developing an Android application and i\'m using a Sqlite database to store some bitmaps. I want some images to be automatically inserted when the user installs the app

2条回答
  •  -上瘾入骨i
    2021-01-04 04:28

    If you really, really want to you can use a very long hex literal as a blob literal:

    insert into memes(img, name) values(X'0102030405060708090a0b0c0d0e0f', '1.jpg')
    

    However, this is usually a bad idea; instead, go look at parameterised queries. They will let you compile a statement once using placeholders instead of actual values, and then reuse it many times, filling in the placeholders as needed:

    SQLiteStatement p = sqlite.compileStatement("insert into memes(img, name) values(?, ?)");
    
    byte[] data = loadData("1.jpg");
    p.bindBlob(1, data);
    p.bindString(2, "1.jpg");
    p.execute();
    
    byte[] data = loadData("2.jpg");
    p.bindBlob(1, data);
    p.bindString(2, "2.jpg");
    p.execute();
    

    (Warning --- code not tested.)

    In general you should be using parameterised queries everywhere, as they're a sure-fire way to avoid SQL injection attacks, plus are usually easier and clearer. Assembling SQL queries by glueing strings together should be avoided at all costs.

提交回复
热议问题