我想使用插入或替换查询,这里我给出的代码,我有
String sql="insert or replace into Stock_Table values (?,?,?,?,?,?)";
sqlite.execSQL(sql, new String[]{id,name,code,vat,itmquan,pric});
现在我想额外插入一个字段到这个表中,但该字段不是字符串这是一个字节数组格式,我想添加一个图像到这个表中,我给这个图像的数据类型作为BLOB在表中,但我不能传递字节数组格式作为一个参数到上面的sqlite。Execsql函数,这里我给出了要插入的格式
byte []byteImage;
String sql="insert or replace into Stock_Table values (?,?,?,?,?,?,?)";
sqlite.execSQL(sql, new String[]{id,name,code,vat,itmquan,pric,byteImage});
我怎么能使它成为可能,我无法将这个字节数组转换成字符串,我想插入图像作为BLOB格式,请帮助我找到任何解决方案
使用insert方法的一个变体,它接受一个ContentValues对象,它允许您直接使用字节数组:
byte[] byteImage;
ContentValues cv = new ContentValues();
cv.put("id", id);
// ...
cv.put("blobcolumn", byteImage);
sqlite.insertWithOnConflict("Stock_Table", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
用这种方法…
@Override
public void onClick(View v) {
SQLiteDatabase myDb;
String MySQL;
int icount;
byte[] byteImage1 = null;
byte[] byteImage2 = null;
MySQL="create table emp1(_id INTEGER primary key autoincrement, fio TEXT not null, picture BLOB);";
myDb = openOrCreateDatabase("/sdcard/MyDB.db", Context.MODE_PRIVATE, null);
// myDb.execSQL(MySQL);
String s=myDb.getPath();
textView.append("rn" + s+"rn");
myDb.execSQL("delete from emp1");
ContentValues newValues = new ContentValues();
newValues.put("fio", "hello dude");
/////////// insert picture to blob field /////////////////////
try
{
FileInputStream instream = new FileInputStream("/sdcard/sunil.png");
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
textView.append("rn" + byteImage1.length+"rn");
newValues.put("picture", byteImage1);
long ret = myDb.insert("emp1", null, newValues);
if(ret<0)
textView.append("rn!!! Error add blob filed!!!rn");
} catch (IOException e)
{
textView.append("rn!!! Error: " + e+"!!!rn");
}
////////////Read data ////////////////////////////
Cursor cur = myDb.query("emp1",null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false)
{
textView.append("rn" + cur.getString(1)+"rn");
cur.moveToNext();
}
///////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2=cur.getBlob(cur.getColumnIndex("picture"));
bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0, byteImage2.length));
textView.append("rn" + byteImage2.length+"rn");
//////////////////////////
cur.close();
myDb.close();
}