当我尝试检查表是否为空时SQLiteException

时间:2013-11-24 21:15:27

标签: android sqlite

当我尝试检查最近的表是否为空时,我得到SQLiteException。我该如何解决这个问题?

这是我的sqlitehelper类:

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    private final static int DATABASE_VERSION = 1;
    private final static String DATABASE_NAME = "LyricsFinderDB";

    public MySQLiteOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        // SQL statement to create recent table
        String CREATE_RECENT_TABLE = "CREATE TABLE recent ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "name INTEGER)";
        database.execSQL(CREATE_RECENT_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        database.execSQL("DROP TABLE IF EXISTS recent");
        this.onCreate(database);
    }

    public boolean isRecentTableEmpty() {
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor = database.rawQuery("SELECT * FROM recent", null);

        if(cursor.getCount() > 0) {
            cursor.close();
            return false;
        }
        cursor.close();
        database.close();
        return true;
    }
}

在MainActivity中,我在此代码中使用它:

if(mySQLiteOpenHelper.isRecentTableEmpty()) {
            //...do something
        } else {
            //...do something
        }

这是我在运行app后得到的例外:

Caused by: android.database.sqlite.SQLiteException: no such table: recent (code 1): , while compiling: SELECT * FROM recent

它引入了这一行:

Cursor cursor = database.rawQuery("SELECT * FROM recent", null);

2 个答案:

答案 0 :(得分:1)

该表不存在。您可以捕获SQLiteException异常,如果它触发创建表并返回TRUE(即表为空)。像这样的东西

try {
    Cursor cursor = database.rawQuery("SELECT * FROM recent", null);
}
catch(SQLiteException e) {
    onCreate(database);
    return TRUE;
}

答案 1 :(得分:0)

首先使用Exception。

看起来你的桌子不存在。