存儲byte數組中
㈠ Android 怎樣用sqlite儲存byte數組
在進行Android開發過程中,我們經常會接觸到Drawable對象(官方開發文檔:A Drawable is a general abstraction for "something that can be drawn."),那麼,若要使用資料庫來進行存儲及讀取.
@Override
public void onCreate(SQLiteDatabase database) {
executeSQLScript(database, "create.sql");
}
private void executeSQLScript(SQLiteDatabase database, string dbname){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
AssetManager assetManager = context.getAssets();
InputStream inputStream = null;
try{
inputStream = assetManager.open(dbname);
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
String[] createScript = outputStream.toString().split(";");
for (int i = 0; i < createScript.length; i++) {
String sqlStatement = createScript[i].trim();
// TODO You may want to parse out comments here
if (sqlStatement.length() > 0) {
database.execSQL(sqlStatement + ";");
}
}
} catch (IOException e){
// TODO Handle Script Failed to Load
} catch (SQLException e) {
// TODO Handle Script Failed to Execute
}
}
㈡ 在java中如何把位元組數組存儲到資料庫
保存位元組數組到資料庫分兩步:
第一、利用FileInputStream.read(byte[])方法把內容讀取到byte[]數組中,比如圖片是由二進制數組成的,就可以定義為一個位元組數組。
第二、在資料庫中對應記錄欄位應該設置為blob類型,這樣就能夠順利保存了
事例代碼如下:
PreparedStatement stmt = connection.generatePreparedStatement("INSERT INTO ... ");
stmt.setBytes(1, yourByteArray);
其中,yourByteArray是你讀出來的字元數組。