数据库是否存在[如何调用类]

时间:2013-01-09 16:50:24

标签: android android-sqlite

我发现了this SQLiteOpenHelper类的优秀示例,它非常好地记录了,我想我可以将它用于我的应用程序;问题是我仍在努力确定我的应用程序创建的数据库是否已存在

我的应用程序有一个主要活动Java类[富有想象力地命名]'ActivityMain',目前调用void dbTest();

public void DBTest() {

        SQLiteDatabase myDB = null;

        /* Create a Database. */
        try {
            myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);

            /* Create a Table in the Database. */
            myDB.execSQL("CREATE TABLE IF NOT EXISTS "
                    + DATABASE_TABLE
                    + " (" + KEY_ID + " integer primary key autoincrement, "
                    + KEY_SCRIPT_NAME + " text, " + KEY_SCRIPT_BODY + " text, "
                    + KEY_SU_NEEDED + " short);");

            /* Insert data to a Table*/
            myDB.execSQL("INSERT INTO "
                    + DATABASE_TABLE
                    + " (" + KEY_SCRIPT_NAME
                    + ", " + KEY_SCRIPT_BODY
                    + ", " + KEY_SU_NEEDED + ")"
                    + " VALUES ('CPU information', 'cat /proc/cpuinfo', 1);");

            /*retrieve data from database */
            Cursor c = myDB.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);

            int scriptName = c.getColumnIndex("name");

            // Check if our result was valid.
            c.moveToFirst();
            // cursor left as it came from the database because it starts at the row before the first row
            ArrayList<String> sData = new ArrayList<String>();
            if (c != null) {
                do {
                    String Name = c.getString(scriptName);
                    sData.add(Name);
                } while (c.moveToNext());
            }

            ListView lv = (ListView) findViewById(R.id.mainListView);
            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, sData));
            lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        } catch (Exception e) {
            Log.e("Error", "Error", e);
        } finally {
            if (myDB != null)
                myDB.close();
        }

在那里它创建数据库,插入一行然后在ListView中显示它,目前这只会在每次启动应用程序时插入相同的行,所以我想检查数据库是否已经存在。< / p>

我希望db开始时有一些初始值,这就是为什么我要插入数据,用户可以删除它,如果他们喜欢

因此,在我的“ActivityMain”课程中,我想从我已使用的“createDataBase();”类调用DatabaseHelper方法,但不能

是这样的:

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

                try {
            createDataBase();
            catch(SQLiteException e){
                // database doesn't exist yet.
                return false;
            }

我在'ActivityMain'类中有一个布尔函数可以正常工作,但我不确定这是正确的方法,事实上应该通过辅助类来完成所有这些/ p>

private boolean checkDatabase() {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        // database doesn't exist yet.
        return false;
    }
    return checkDB != null ? true : false;
}

有人可以给我一些指示吗?

非常感谢:)

3 个答案:

答案 0 :(得分:1)

教程很好但不像official API documentation。请务必阅读官方文档。教程,为了简单起见,总是省略东西(有时是重要的东西)。

如您所见,如果数据库不存在,getReadableDatabse()和/或getWritableDatabase()会自动调用onCreate()

以下是我如何做的示例(未经测试,但应告诉您如何操作):

public class YourDBManager extends SQLiteOpenHelper {

    private SQLiteDatabase db = null;

    public YourDBManager(final Context context, final String dbName, final int dbVersion) {
        super(context, dbName, null, dbVersion);
        db = getWritableDatabase();
    }

    /** Initializes your DB */
    private void initializeDB(final SQLiteDatabase db) throws SQLException {
        // Do whatever you want to do to initialize your DB here
    }

    /** 
     * This method is NOT called directly by you but called by SQLiteOpenHelper, 
     * but by getReadableDatabase()/getWritableDatabase() in case it doesn't exist.
     * Here you do whatever you want to do to initialize the DB the first time it is created.
     */
    @Override
    public void onCreate(final SQLiteDatabase db) throws SQLException {
        Log.i(TAG, "=====DATABASE DOES NOT EXIST: CREATING IT======");
        initializeDB(db);
    }
}

public class YourActivity extends Activity {

    private YourDBManager dbMan = null;

    /** Do NOT call from UIThread! */
    private void initializeDBManager() {
        dbMan = new YourDBManager(this, "mydatabase", 1);
    }
}

希望这有帮助。

答案 1 :(得分:1)

您可以使用

查看数据库文件是否存在
File dbFile = context.getDatabasePath(DATABASE_NAME);
if(dbFile.exists()){
// do something
}

这不会告诉您数据库是否有效或者是否有效。

答案 2 :(得分:1)

我认为你已经以正确的方式做事了。关于该主题还有一些其他问题(例如Query if Android database exists!Android - Does SQLite Database Exist?)建议打开数据库,然后捕获异常以显示数据库不存在。