存储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是你读出来的字符数组。