insert returns error code 8 attempt to write a readonly database
Where is the database on the phone? In the resources directory, or did you copy it to the Documents directory? The resources directory is read-only.
android資源文件下的resource 或者raw文件下的 .db文件和ios打包的.db文件只有訪問權(quán)限编丘,如果要對數(shù)據(jù)庫進行寫入則必須重新copy數(shù)據(jù)庫到指定文件目錄,android可以copy到sdcard里面再進行寫入;
objec-c代碼:
/**
* copy db文件放入app目錄
*
* @param mDataBaseName 文件名
*/
+(void)copyDB2Document:(NSString *)mDataBaseName
{
BOOL success;
NSError *error;
NSFileManager *filemanagr = [NSFileManager defaultManager];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dbPath = [path objectAtIndex:0];
NSString *finalDBPath = [dbPath stringByAppendingPathComponent:mDataBaseName];
success = [filemanagr fileExistsAtPath:finalDBPath];
if (success) {
NSLog(@"db 已copy到文件目錄");
}
else
{
NSString *writableDBPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:mDataBaseName];
success = [filemanagr copyItemAtPath:writableDBPath toPath:finalDBPath error:&error];
}
if (!success) {
NSLog(@"db 已copy到文件目錄失敗");
}else{
NSLog(@"db 已copy到文件目錄成功");
}
}
android代碼:
/**
* copy raw文件下面的db文件到應(yīng)用data目錄下
* @param dbFileName 文件名稱
* @param mContext 上下文應(yīng)用對象
* @param rawResId 資源文件id
*/
public static void copyDB2Data(String dbFileName,Context mContext,int rawResId){
//獲取應(yīng)用包名
String packageName = mContext.getPackageName();
String filePath = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + packageName;
File file = new File(filePath);
// if(file.exists()){
// file.delete();
// }
if (!file.exists()) {
// // 打開raw中得數(shù)據(jù)庫文件,獲得stream流
InputStream stream = mContext.getResources().openRawResource(rawResId);
try {
// 將獲取到的stream 流寫入道data中
FileOutputStream outputStream = new FileOutputStream(filePath);
byte[] buffer = new byte[4096];
int count = 0;
while ((count = stream.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
}
outputStream.close();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}