SQLite
 sql >> Baza danych >  >> RDS >> SQLite

Czy powinienem utworzyć klasę, która dziedziczy SQLiteOpenHelper dla każdej tabeli w mojej bazie danych?

Potrzebujesz tylko jednego pomocnika bazy danych dla wszystkich tabel w bazie danych, a zatem użyjesz jednego onCreate metoda tworzenia tabel. Zauważając, że jeśli masz wielu pomocników bazy danych, onCreate (i w aktualizacji metoda) zostanie wywołana tylko raz przez pierwszego pomocnika, który otworzył bazę danych, a zatem oprócz tego, że wielu pomocników jest nieefektywnych, posiadanie wielu pomocników bazy danych może być bardziej skomplikowane.

Dokładniej onCreate jest wywoływana automatycznie tylko wtedy, gdy baza danych nie istnieje. Do czasu naCreate nazywa się sama baza danych została utworzona.

w aktualizacji jest wywoływana tylko wtedy, gdy po otwarciu bazy danych numer wersji przekazany do wywołania (poprzez super wywołanie) jest większy niż numer wersji zapisany w pliku bazy danych. Numer wersji przechowywany w pliku jest w tym momencie aktualizowany w celu odzwierciedlenia nowszej wersji. Dlatego kolejne wywołania nie będą wtedy wywoływać onUpgrade metoda.

Możesz dokonać wyboru, czy podzielisz metody i identyfikatory, takie jak nazwy kolumn/tabeli dla poszczególnych tabel. Niektórzy mogą uważać, że podział jest niezręczny, inni mogą uważać, że jest to jaśniejsze.

Przykład

Poniższy kod jest przykładem 3 permutacji (a także baz danych), z których każda wykorzystuje 2 tabele, a mianowicie table001 (kolumny _id i moje dane ) i table001 (nazwy kolumn _id i mojeinnedane ).

  1. używa pojedynczej bazy danychHelper (DBHelper001) ze wszystkim osadzonym w helperze. Baza danych to mydb001

  2. używa pojedynczego pomocnika bazy danych (DBHelper002) z metodami i stałymi specyficznymi dla tabeli w określonych klasach zorientowanych na tabele (klasa Table001 i klasa Table002).

  3. używa dwóch oddzielnych pomocników baz danych (DBHelperTable001 i DBHelperTable002), a dla uproszczenia kodu używa klas Table001 i Table002.

    • Pamiętaj, że aby pokonać onCreate wywołanie tylko raz onOpen metoda również próbuje utworzyć odpowiednią tabelę (CREATE TABLE IF NOT EXISTS ...... w tym przypadku ważne jest, aby uniknąć awarii, gdy tabela faktycznie istnieje).
    • Zauważ, że to tylko jedna nieefektywność posiadania wielu pomocników.

Najpierw klasy specyficzne dla tabeli (nie używane przez pierwszą permutację)

Tabela001.java

public class Table001 {

    public static final String TBL_TABLE001 = "table001";
    public static final String COL_TABLE001_ID = BaseColumns._ID;
    public static final String COL_TABLE001_MYDATA = "mydata";

    public static String getCrtSQL() {
        return "CREATE TABLE IF NOT EXISTS " + TBL_TABLE001 + "(" +
                COL_TABLE001_ID + " INTEGER PRIMARY KEY, " +
                COL_TABLE001_MYDATA + " TEXT" +
                ")";
    }

    public static long insert(SQLiteDatabase db, String mydata) {
        ContentValues cv = new ContentValues();
        cv.put(COL_TABLE001_MYDATA,mydata);
        return db.insert(TBL_TABLE001,null,cv);
    }

    public static Cursor getAll(SQLiteDatabase db) {
        return db.query(TBL_TABLE001,null,null,null,null,null,null);
    }
}

Tabela002.java

public class Table002 {

    public static final String TBL_TABLE002 = "table002";
    public static final String COL_TABLE002_ID = BaseColumns._ID;
    public static final String COL_TABLE002_MYOTHERDATA = "myotherdata";

    public static String getCrtSQL() {
        return "CREATE TABLE IF NOT EXISTS " + TBL_TABLE002 + "(" +
                COL_TABLE002_ID + " INTEGER PRIMARY KEY, " +
                COL_TABLE002_MYOTHERDATA + " TEXT" +
                ")";
    }

    public static long insert(SQLiteDatabase db, String mydata) {
        ContentValues cv = new ContentValues();
        cv.put(COL_TABLE002_MYOTHERDATA,mydata);
        return db.insert(TBL_TABLE002,null,cv);
    }

    public static Cursor getAll(SQLiteDatabase db) {
        return db.query(TBL_TABLE002,null,null,null,null,null,null);
    }
}

Cztery klasy pomocnicze bazy danych

DBHelper001.java — (samodzielny)

public class DBHelper001 extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb001";
    public static final int DBVERSION = 1;

    public static final String TBL_TABLE001 = "table001";
    public static final String TBL_TABLE002 = "table002";
    public static final String COL_TABLE001_ID = BaseColumns._ID;
    public static final String COL_TABLE001_MYDATA = "mydata";
    public static final String COL_TABLE002_ID = BaseColumns._ID;
    public static final String COL_TABLE002_MYOTHERDATA = "myotherdata";

    public DBHelper001(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crt_table001_sql = "CREATE TABLE IF NOT EXISTS " + TBL_TABLE001 + "(" +
                COL_TABLE001_ID + " INTEGER PRIMARY KEY," +
                COL_TABLE001_MYDATA + " TEXT" +
                ")";
        String crt_table002_sql = "CREATE TABLE IF NOT EXISTS " + TBL_TABLE002 + "(" +
                COL_TABLE002_ID + " INTEGER PRIMARY KEY," +
                COL_TABLE002_MYOTHERDATA + " TEXT" +
                ")";
        db.execSQL(crt_table001_sql);
        db.execSQL(crt_table002_sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insertIntoTable001(String mydata) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COL_TABLE001_MYDATA,mydata);
        return db.insert(TBL_TABLE001,null,cv);
    }

    public long insertIntoTable002(String myotherdata) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COL_TABLE002_MYOTHERDATA,myotherdata);
        return db.insert(TBL_TABLE002,null,cv);
    }

    public Cursor getAllFromTable001() {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.query(TBL_TABLE001,null,null,null,null,null,null);
    }

    public Cursor getAllFromTable002() {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.query(TBL_TABLE002,null,null,null,null,null,null);
    }
}

DBHelper002.java (kod specyficzny dla tabeli w innym miejscu)

public class DBHelper002 extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb002";
    public static final int DBVERSION = 1;

    public DBHelper002(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Table001.getCrtSQL());
        db.execSQL(Table002.getCrtSQL());
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

DBHelperTable001.java (pomocnik specyficzny dla Table001)

public class DBHelperTable001 extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb003";
    public static final int DBVERSION = 1;

    public DBHelperTable001(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Table001.getCrtSQL());
        //NOTE Table002 won't get created as onCreate is only called once
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        db.execSQL(Table001.getCrtSQL());
    }
}
  • Uwaga onOpen Metoda służy do obejścia onCreate tylko raz wywołanego przez cały okres istnienia bazy danych.
    • Wywołanie execSQL jest przykładem nieefektywności tej metodologii.

DBHelperTable002.java (pomocnik specyficzny dla Table002)

public class DBHelperTable002 extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb003";
    public static final int DBVERSION = 1;

    public DBHelperTable002(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Table002.getCrtSQL());
        //NOTE Table001 won't get created as onCreate is only called once
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        db.execSQL(Table002.getCrtSQL());
    }
}

Łączenie ich wszystkich razem

Następujące działanie wykorzystuje (MainActivity.java ) wykorzystuje wszystkie 3 permutacje. Dla każdego dodawany jest wiersz do każdej tabeli, a następnie wszystkie dane z każdej tabeli są wyodrębniane do kursora, który jest następnie zrzucany (wyprowadzany do dziennika).

Zwróć uwagę, że w przypadku pomocników specyficznych dla tabeli każdy pomocnik jest używany do wyodrębniania wierszy (pokazując aspekt nadmiarowości).

Aktywność główna.java

public class MainActivity extends AppCompatActivity {

    DBHelper001 mDBHlpr1;
    DBHelper002 mDBHlpr2;
    DBHelperTable001 mTblDBHlpr1;
    DBHelperTable002 mTblDBHlpr2;
    Cursor mCsr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDBHlpr1 = new DBHelper001(this);
        mDBHlpr1.insertIntoTable001("my data for table001 in mydb001");
        mDBHlpr1.insertIntoTable002("my other data for table002 in mydb001");
        mCsr = mDBHlpr1.getAllFromTable001();
        DatabaseUtils.dumpCursor(mCsr);
        mCsr = mDBHlpr1.getAllFromTable002();
        DatabaseUtils.dumpCursor(mCsr);


        mDBHlpr2 = new DBHelper002(this);
        Table001.insert(mDBHlpr2.getWritableDatabase(),"my data for table001 in mydb002");
        Table002.insert(mDBHlpr2.getWritableDatabase(),"my other data for table002 in mydb002");
        mCsr = Table001.getAll(mDBHlpr2.getWritableDatabase());
        DatabaseUtils.dumpCursor(mCsr);
        mCsr = Table002.getAll(mDBHlpr2.getWritableDatabase());
        DatabaseUtils.dumpCursor(mCsr);

        //Oooops???? wouldn't normally do this
        mCsr = Table001.getAll(mDBHlpr1.getWritableDatabase()); //?????????? from other database!!!
        DatabaseUtils.dumpCursor(mCsr);

        mTblDBHlpr1 = new DBHelperTable001(this);
        Table001.insert(mTblDBHlpr1.getWritableDatabase(),"my data for table001 in mydb003");
        mTblDBHlpr2 = new DBHelperTable002(this);
        Table002.insert(mTblDBHlpr2.getWritableDatabase(),"my data for table002 in mydb003");
        mCsr = Table001.getAll(mTblDBHlpr1.getWritableDatabase());
        DatabaseUtils.dumpCursor(mCsr);
        mCsr = Table002.getAll(mTblDBHlpr1.getWritableDatabase()); //???????????? but OK
        DatabaseUtils.dumpCursor(mCsr);
        mCsr = Table001.getAll(mTblDBHlpr2.getWritableDatabase());
        DatabaseUtils.dumpCursor(mCsr);
        mCsr = Table002.getAll(mTblDBHlpr2.getWritableDatabase()); //??????????? but OK
        DatabaseUtils.dumpCursor(mCsr);
    }
}

Wynik

Poniżej znajduje się wynik pierwszego uruchomienia (notatka uruchomiona wiele razy bez odinstalowywania aplikacji spowoduje dodanie 2 nowych wierszy):-

03-06 11:27:18.453 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.453 11093-11093/? I/System.out: 0 {
03-06 11:27:18.453 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.453 11093-11093/? I/System.out:    mydata=my data for table001 in mydb001
03-06 11:27:18.453 11093-11093/? I/System.out: }
03-06 11:27:18.453 11093-11093/? I/System.out: <<<<<
03-06 11:27:18.453 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.453 11093-11093/? I/System.out: 0 {
03-06 11:27:18.453 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.453 11093-11093/? I/System.out:    myotherdata=my other data for table002 in mydb001
03-06 11:27:18.453 11093-11093/? I/System.out: }
03-06 11:27:18.453 11093-11093/? I/System.out: <<<<<


03-06 11:27:18.472 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.472 11093-11093/? I/System.out: 0 {
03-06 11:27:18.472 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.472 11093-11093/? I/System.out:    mydata=my data for table001 in mydb002
03-06 11:27:18.472 11093-11093/? I/System.out: }
03-06 11:27:18.472 11093-11093/? I/System.out: <<<<<
03-06 11:27:18.472 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.473 11093-11093/? I/System.out: 0 {
03-06 11:27:18.473 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.473 11093-11093/? I/System.out:    myotherdata=my other data for table002 in mydb002
03-06 11:27:18.473 11093-11093/? I/System.out: }
03-06 11:27:18.473 11093-11093/? I/System.out: <<<<<


03-06 11:27:18.473 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.473 11093-11093/? I/System.out: 0 {
03-06 11:27:18.473 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.473 11093-11093/? I/System.out:    mydata=my data for table001 in mydb001
03-06 11:27:18.473 11093-11093/? I/System.out: }
03-06 11:27:18.473 11093-11093/? I/System.out: <<<<<


03-06 11:27:18.499 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.500 11093-11093/? I/System.out: 0 {
03-06 11:27:18.500 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.500 11093-11093/? I/System.out:    mydata=my data for table001 in mydb003
03-06 11:27:18.500 11093-11093/? I/System.out: }
03-06 11:27:18.500 11093-11093/? I/System.out: <<<<<
03-06 11:27:18.500 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.500 11093-11093/? I/System.out: 0 {
03-06 11:27:18.501 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.501 11093-11093/? I/System.out:    myotherdata=my data for table002 in mydb003
03-06 11:27:18.501 11093-11093/? I/System.out: }
03-06 11:27:18.501 11093-11093/? I/System.out: <<<<<
03-06 11:27:18.501 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.501 11093-11093/? I/System.out: 0 {
03-06 11:27:18.501 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.501 11093-11093/? I/System.out:    mydata=my data for table001 in mydb003
03-06 11:27:18.501 11093-11093/? I/System.out: }
03-06 11:27:18.502 11093-11093/? I/System.out: <<<<<
03-06 11:27:18.502 11093-11093/? I/System.out: >>>>> Dumping cursor [email protected]
03-06 11:27:18.502 11093-11093/? I/System.out: 0 {
03-06 11:27:18.502 11093-11093/? I/System.out:    _id=1
03-06 11:27:18.502 11093-11093/? I/System.out:    myotherdata=my data for table002 in mydb003
03-06 11:27:18.503 11093-11093/? I/System.out: }
03-06 11:27:18.503 11093-11093/? I/System.out: <<<<<



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Integracja SQLCipher z greenDAO

  2. android.database.sqlite.SQLiteException:blisko s:błąd składni (kod 1):,

  3. Grupuj SQLite według/licz godziny, dni, tygodnie, rok

  4. Jak uzyskać dostęp i zaktualizować plik db Sqlite przechowywany lokalnie [folder zasobów] w pliku projektu za pomocą cordova?

  5. Jak mogę utworzyć listę Array z danymi kursora w Androidzie?