微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – SQLite – 是否可以通过insert语句插入BLOB?

我正在开发一个 Android应用程序,我正在使用一个sqlite数据库来存储一些位图.当用户安装应用程序时,我想要自动插入一些图像.

我正在使用sqliteOpenHelper类:

public class DatabaseHelper extends sqliteOpenHelper {

...

DatabaseHelper(Context context,String nameOfdb,int version,String[] scriptsqlCreate,String scriptsqlDelete) {
    super(context,nameOfdb,null,version);

    this.scriptsqlCreate = scriptsqlCreate;
    this.scriptsqlDelete = scriptsqlDelete;
}

@Override
public void onCreate(sqliteDatabase db) {
    int numScripts = scriptsqlCreate.length;
    for(int i = 0; i<numScripts; i++){
    Log.i(TAG,"Creating database,executing script " + i);
    db.execsql(scriptsqlCreate[i]);
    }
}
}

我想传递一个常量到上面显示的scriptsqlCreate参数,就像这样:

private static final String[] SCRIPT_DATABASE_CREATE = {
   "create table memes(  id integer primary key autoincrement," + 
                     + " img blob not null," + 
                     + " name text not null unique)","insert into memes(img,name) values(BITMAP1,'1.jpg')",name) values(BITMAP2,'2.jpg')",name) values(BITMAP3,'3.jpg')"}    

}

任何帮助将会很多,

谢谢,
Tulio Zahn

解决方法

如果你真的,真的希望你可以使用一个非常长的十六进制文字作为一个blob字面量:
insert into memes(img,name) values(X'0102030405060708090a0b0c0d0e0f','1.jpg')

但是,这通常是一个坏主意;相反,请看看parameterised queries.他们将让您编写一次使用占位符而不是实际值的语句,然后重复使用多次,根据需要填写占位符:

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,"2.jpg");
p.execute();

(警告—代码未测试.)

一般来说,您应该在任何地方使用参数化查询,因为它们是一种可靠的方式来避免sql注入攻击,另外通常更容易和更清晰.应该不惜一切代价避免将字符串混合在一起来组合SQL查询.

原文地址:https://www.jb51.cc/android/311394.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐