2012-01-16 95 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)檢查你的數據庫文件。請注意表格中的錯誤詞。