2012-01-16 93 views
11

我正在开发一个Android应用程序,我正在使用Sqlite数据库来存储一些位图。我想要在用户安装应用程序时自动插入一些图像。SQLite - 是否可以通过插入语句插入BLOB?

我使用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')", 
    "insert into memes(img,name) values(BITMAP2,'2.jpg')", 
    "insert into memes(img,name) values(BITMAP3,'3.jpg')"}  

} 

任何帮助将大大降低,

THX, 图略赞恩

回答

16

如果你真的想你可以使用一个很长的十六进制文字作为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, data); 
p.bindString(2, "2.jpg"); 
p.execute(); 

(警告---代码没有测试)。

一般来说,您应该使用参数化查询无处不在,因为它们确实是避免SQL注入攻击的一种方式,而且通常更简单,更清晰。不惜一切代价避免通过将字符串粘合在一起来组装SQL查询。

+0

Humm,你的方法绝对有趣。如果需要用数百个位图预先填充数据库,而不是少数几个,则更是如此。在这种情况下,拥有数百个插入语句变得非常不切实际。我会测试你的方法,但首先我必须想出一个解决所有这些图像的问题的解决方案。在他们中有很多的情况下,只是把它们放在可绘制的文件夹中似乎也是非常不切实际的 – tulio84z 2012-01-16 18:46:13

+1

你想要的是你的项目中的资产目录---有一个API可以让你在那里访问文件,重新在文件系统上的真实文件:http://developer.android.com/reference/android/content/res/AssetManager.html – 2012-01-17 10:31:04

0

您的数据表有一些您看不到的隐形字。用数据库工具(如navicat for sqlite)检查你的数据库文件。请注意表格中的错误词。