Programing

Android SQLite 데이터베이스에 테이블이 있는지 어떻게 확인합니까?

lottogame 2020. 9. 23. 08:04
반응형

Android SQLite 데이터베이스에 테이블이 있는지 어떻게 확인합니까?


데이터베이스에 이미 레코드가 있는지 확인하고 그렇지 않은 경우 일부를 처리하고 결국 삽입하고 데이터가 존재하는 경우 데이터베이스에서 데이터를 읽어야하는 Android 앱이 있습니다. SQLiteOpenHelper의 하위 클래스를 사용하여 SQLiteDatabase의 재기록 가능한 인스턴스를 만들고 가져오고 있는데, 테이블이 아직 존재하지 않는 경우 자동으로 테이블을 생성한다고 생각했습니다 (이 작업을 수행하는 코드는 onCreate (... ) 방법).

그러나 테이블이 아직 존재하지 않고 내가 가지고있는 SQLiteDatabase 객체에서 실행 된 첫 번째 메서드가 query (...)에 대한 호출 인 경우 내 logcat에 "I / Database (26434) : sqlite returned : error code = 1, msg = no such table : appdata "이며, 확실히 appdata 테이블이 생성되지 않습니다.

이유에 대한 아이디어가 있습니까?

나는 테이블이 존재하는지 테스트하는 방법을 찾고 있습니다 (그렇지 않으면 데이터가 확실히 거기에 없기 때문에 테이블을 만드는 것처럼 보일 때까지 읽을 필요가 없기 때문입니다. 적절하게) 또는 query (...)에 대한 첫 번째 호출 시간 내에 생성되고 비어 있는지 확인하는 방법

편집
이것은 아래 두 가지 답변 후에 게시되었습니다
. 문제를 발견했을 수 있다고 생각합니다. 나는 어떤 이유로 든 동일한 데이터베이스 파일에 액세스하더라도 각 테이블에 대해 다른 SQLiteOpenHelper를 만들어야한다고 결정했습니다. 하나의 OpenHelper 만 사용하도록 해당 코드를 리팩토링하고 onCreate 안에 두 테이블을 모두 만드는 것이 더 잘 작동 할 수 있다고 생각합니다.


이거 한번 해봐:

public boolean isTableExists(String tableName, boolean openDb) {
    if(openDb) {
        if(mDatabase == null || !mDatabase.isOpen()) {
            mDatabase = getReadableDatabase();
        }

        if(!mDatabase.isReadOnly()) {
            mDatabase.close();
            mDatabase = getReadableDatabase();
        }
    }

    String query = "select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'";
    try (Cursor cursor = mDatabase.rawQuery(query, null)) {
        if(cursor!=null) {
            if(cursor.getCount()>0) {
                return true;
            }
        }
        return false;
    }
}

Android SQLite API에 대해 아무것도 모르지만 SQL에서 직접 대화 할 수 있다면 다음과 같이 할 수 있습니다.

create table if not exists mytable (col1 type, col2 type);

이렇게하면 테이블이 항상 생성되고 이미 존재하는 경우 오류가 발생하지 않습니다.


이것이 내가 한 일입니다.

/* open database, if doesn't exist, create it */
SQLiteDatabase mDatabase = openOrCreateDatabase("exampleDb.db", SQLiteDatabase.CREATE_IF_NECESSARY,null);

Cursor c = null;
boolean tableExists = false;
/* get cursor on it */
try
{
    c = mDatabase.query("tbl_example", null,
        null, null, null, null, null);
        tableExists = true;
}
catch (Exception e) {
    /* fail */
    Log.d(TAG, tblNameIn+" doesn't exist :(((");
}

return tableExists;

이 질문에 대한 좋은 답은 이미 많이 있지만 더 간단하다고 생각되는 또 다른 해결책을 찾았습니다. 쿼리를 try 블록과 다음 catch로 묶습니다.

catch (SQLiteException e){
    if (e.getMessage().contains("no such table")){
            Log.e(TAG, "Creating table " + TABLE_NAME + "because it doesn't exist!" );
            // create table
            // re-run query, etc.
    }
}

그것은 나를 위해 일했습니다!


네, 내 편집의 이론이 옳았습니다. onCreate 메서드가 실행되지 않는 문제는 SQLiteOpenHelper개체가 데이터베이스를 참조해야하고 각 테이블에 대해 별도의 데이터베이스가 없어야 한다는 사실이었습니다 . 두 테이블을 하나로 묶어 SQLiteOpenHelper문제가 해결되었습니다.


You mentioned that you've created an class that extends SQLiteOpenHelper and implemented the onCreate method. Are you making sure that you're performing all your database acquire calls with that class? You should only be getting SQLiteDatabase objects via the SQLiteOpenHelper#getWritableDatabase and getReadableDatabase otherwise the onCreate method will not be called when necessary. If you are doing that already check and see if th SQLiteOpenHelper#onUpgrade method is being called instead. If so, then the database version number was changed at some point in time but the table was never created properly when that happened.

As an aside, you can force the recreation of the database by making sure all connections to it are closed and calling Context#deleteDatabase and then using the SQLiteOpenHelper to give you a new db object.


 // @param db, readable database from SQLiteOpenHelper

 public boolean doesTableExist(SQLiteDatabase db, String tableName) {
        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;
}
  • sqlite maintains sqlite_master table containing information of all tables and indexes in database.
  • So here we are simply running SELECT command on it, we'll get cursor having count 1 if table exists.

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

no such table exists: error is coming because once you create database with one table after that whenever you create table in same database it gives this error.

To solve this error you must have to create new database and inside the onCreate() method you can create multiple table in same database.


Important condition is IF NOT EXISTS to check table is already exist or not in database

like...

String query = "CREATE TABLE IF NOT EXISTS " + TABLE_PLAYER_PHOTO + "("
            + KEY_PLAYER_ID + " TEXT,"
            + KEY_PLAYER_IMAGE + " TEXT)";
db.execSQL(query);

..... Toast t = Toast.makeText(context, "try... " , Toast.LENGTH_SHORT); t.show();

    Cursor callInitCheck = db.rawQuery("select count(*) from call", null);

    Toast t2a = Toast.makeText(context, "count rows " + callInitCheck.getCount() , Toast.LENGTH_SHORT);
    t2a.show();

    callInitCheck.moveToNext();
    if( Integer.parseInt( callInitCheck.getString(0)) == 0) // if no rows then do
    {
        // if empty then insert into call

.....

참고URL : https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database

반응형