Android-无法写入数据库

时间:2015-06-12 15:54:12

标签: android database sqlite

我遇到了与SQLite数据库的Android应用程序连接问题。我在Assets文件夹中有一个SQLite数据库实例。 '选择' operation返回手动插入数据库的数据。但是,Write操作(Insert,Update,Delete)失败。我正在使用' this.getReadableDatabase()'并替换为' this.getWritableDatabase',同样, SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY)已替换为SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE),但仍无用。我正在使用2.3.6版本的三星Galaxy S i-90003进行测试。有人请帮帮我

    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
   // values.put(KEY_ID,contact.getId());//Contact Id
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_IMAGE, contact.getImage()); // Contact Phone
    // Inserting Row
    try {
        if(isTableExists(TABLE_IMAGES,true)) {
            db.insert(TABLE_IMAGES, null, values);
        }
    }catch (Exception e) {
        System.out.println("Error inserting:"+e.getMessage());
    }
    db.close(); // Closing database connection

   public boolean isTableExists(String tableName, boolean openDb) {
    if(openDb) {
        if(db == null || !db.isOpen()) {
            db = getWritableDatabase();
        }
        if(!db.isReadOnly()) {
            db.close();
            db = getWritableDatabase();
        }
    }
    Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master  where tbl_name = '"+tableName+"'", null);
    if(cursor!=null) {
        if(cursor.getCount()>0) {
            cursor.close();
            return true;
        }
        cursor.close();
    }
    return false;
}

1 个答案:

答案 0 :(得分:0)

问题似乎与数据库的写权限有关。 Android为您提供了这两种方法来管理新数据库的创建和升级

public class MyDBHandler extends SQLiteOpenHelper {

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        //add here the sql code to create the database

    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // everytime you need to change the database place your sql code here

    }
}

您应该按照本教程了解如何更正它 the documentation for NSSession