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文件只有访问权限,如果要对数据库进行写入则必须重新copy数据库到指定文件目录,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文件到应用data目录下
* @param dbFileName 文件名称
* @param mContext 上下文应用对象
* @param rawResId 资源文件id
*/
public static void copyDB2Data(String dbFileName,Context mContext,int rawResId){
//获取应用包名
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中得数据库文件,获得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();
}
}
}
网友评论