簡體   English   中英

在SQLite數據庫的多個表上插入和更新數據

[英]Inserting and updating data on multiple table on SQLite database

在我的項目中,我使用一個類來創建一個SQLite數據庫,該類將android中的SQLiteOpenHelper庫擴展為在一個數據庫中創建三個表。 問題是當在MainActivity類中(如下)時,我想創建和更新數據行,而不是將數據放在所需的表中,而是僅保存在“ table3db”表中,而其他表仍然為空 (我看到了這種情況應用程序可以瀏覽SQLite數據庫),但我想將每個數據保存在所需的表中。 例如,第一個和第二個數據必須保存在第一個表中,第三個數據必須保存在第二個表中,第四個數據整數必須保存在第三個表中。

表

我該怎么做才能解決這個問題?

第一步,我在DatabaseHelper使用以下代碼創建了三個表:

public class DatabaseHelper extends SQLiteOpenHelper {

    private final String TAG = "DatabaseHelper";
    private static final String DATABASE_NAME = "db";    
    private static final int DATABASE_VERSION = 1;

    private static final String COLUMN_ID      = "_id";
    private static final String COLUMN_NAME    = "name";
    private static final String COLUMN_VALUE   = "value";
    private static final String COLUMN_VALUE2 = "value2";
    private static final String TABLE_NAME     = "table1db";
    private static final String CREATE_TABLE   = "CREATE TABLE " + TABLE_NAME + " (" + 
        COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
        COLUMN_NAME + " INTEGER," +
        COLUMN_VALUE + " INTEGER," +
        COLUMN_VALUE2 + " TEXT" +
        ");";

    private static final String COLUMN_ID_2    = "_id";
    private static final String COLUMN_NAME_2  = "name";
    private static final String COLUMN_VALUE_2 = "value";
    private static final String COLUMN_VALUE2_2 = "value2";
    private static final String TABLE_NAME_2   = "table2db";
    private static final String CREATE_TABLE_2   = "CREATE TABLE " + TABLE_NAME_2 + " (" + 
            COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COLUMN_NAME_2 + " INTEGER," +
            COLUMN_VALUE_2 + " INTEGER," +
            COLUMN_VALUE2_2 + " TEXT" +
            ");";

    private static final String COLUMN_ID_3    = "_id";
    private static final String COLUMN_NAME_3  = "name";
    private static final String COLUMN_VALUE_3 = "value";
    private static final String COLUMN_VALUE2_3 = "value2";
    private static final String TABLE_NAME_3   = "table3db";
    private static final String CREATE_TABLE_3   = "CREATE TABLE " + TABLE_NAME_3 + " (" + 
            COLUMN_ID_3 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COLUMN_NAME_3 + " INTEGER," +
            COLUMN_VALUE_3 + " INTEGER," +
            COLUMN_VALUE2_3 + " TEXT" +
            ");";

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_2);
        Log.i(TAG, "editTexts Table created.");

        db.execSQL(CREATE_TABLE);
        Log.i(TAG, "Table created.");

        db.execSQL(CREATE_TABLE_3);
        Log.i(TAG, "Table created.");
    }

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.i(TAG, "Object created.");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        newVersion=oldVersion+1;
        Log.w(TAG, "Upgrading database from version " + oldVersion 
                + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + ";");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");

        onCreate(db);
    }

    public String getTableName(int tableNumber) {
        String out="";
        switch (tableNumber){
        case 1:
            out=TABLE_NAME;
        case 2:
            out=TABLE_NAME_2;
        case 3:
            out=TABLE_NAME_3;
        }
        return out;
    }

    public String getRowIdName(int tableNumber) {
        String out="";
        switch (tableNumber){
        case 1:
            out=COLUMN_ID;
        case 2:
            out=COLUMN_ID_2;
        case 3:
            out=COLUMN_ID_3;
        }
        return out;
    }
}

然后,我創建了該類以將DatabaseHelper類與以下代碼一起使用,名稱為DatabaseHandler

public class DatabaseHandler {

    private final String TAG      = "DatabaseHandler";
    static final  String NAME    = "name";
    static final  String VALUE   = "value";
    static final  String VALUE2  = "value2";
    private DatabaseHelper dbHelper;
    private SQLiteDatabase database;

    public DatabaseHandler(Context context) {
        dbHelper = new DatabaseHelper(context);
        Log.i(TAG, "DatabaseHelper Object created.");
    }

    public void open() throws SQLException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    public void insertCBox(int tableNumber, CBox checkBox) {
        ContentValues cv = new ContentValues();

        cv.put(NAME,  checkBox.getName());
        cv.put(VALUE, checkBox.getStatus());
        cv.put(VALUE2, checkBox.getText());
        database.insert(dbHelper.getTableName(tableNumber), NAME, cv);

        Log.i(TAG, "Contact added successfully.");
    }

    public void deleteCheckBox(int tableNumber, int id) {
        database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
    }

    public void updateCheckBox(int tableNumber, int id,int name,int state, String text) {

        ContentValues cv = new ContentValues();
        cv.put(NAME,  name);
        cv.put(VALUE, state);
        cv.put(VALUE2, text);
        database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
    }

    public CBox getCBox(int tableNumber, int id){
        Log.i(TAG, "getCBOX started");
        Cursor cursor = database.query(dbHelper.getTableName(tableNumber), null, null, null, null, null, null);
        Log.i(TAG, "cursor query done");
        cursor.moveToFirst();
        cursor.moveToPosition(id-1);
        Log.i(TAG, "cursor is here: "+ cursor.getPosition());
//        cursor.moveToPosition(id--);
        Log.i(TAG, "cursor moved to position successfully "+ id--);
        CBox CBox = cursorToContact(cursor);
        Log.i(TAG, "cursor to contact done");
        cursor.close();
        Log.i(TAG, "cursor closed");
        return CBox;
    }


    public void clearTable(int tableNumber) {
        database.delete(dbHelper.getTableName(tableNumber), null, null);
    }

    private CBox cursorToContact(Cursor cursor) {
        CBox checkBox = new CBox();
        Log.i(TAG, "cursor to contact > started");
        checkBox.setId(cursor.getInt(0));
        Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
        checkBox.setName(cursor.getInt(1));
        Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
        checkBox.setStatus(cursor.getInt(2));
        Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
        checkBox.setText(cursor.getString(3));
        Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());

        return checkBox;
    }

}

Mainactivity類的第三步中,我使用以下代碼來使用數據庫以及插入,更新和保存數據:

public class MainActivity extends Activity {

    private DatabaseHandler dbHandler;
    private static final int databaseTableNumber1=1;
    private static final int databaseTableNumber2=2;
    private static final int databaseTableNumber3=3;

    private CBox cBox01;
    private CBox cBox02;
    private CBox cBox03;
    private CBox cBox04;

    private boolean firstRunPassed=false;
    private SharedPreferences sharedperefs;
       private String preferenceName = "Preferences";

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Log.i(TAG, "On Create");
        setContentView(R.layout.activity_main);

        dbHandler = new DatabaseHandler(this);

        final Button saveButton = (Button) findViewById(R.id.saveButton);         
        saveButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHandler.open();
                int state;
                String text;
                CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
                if(checkBox01.isChecked()) state=1; else state=0;
                dbHandler.updateCheckBox(databaseTableNumber1,1,R.id.checkBox1,state,"");

                RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
                state= radioGroup01.getCheckedRadioButtonId();
                dbHandler.updateCheckBox(databaseTableNumber1,2, R.id.radioGroup1, state,"");

                EditText editText01=(EditText) findViewById(R.id.editText1);
                text=editText01.getText().toString();
                dbHandler.updateCheckBox(databaseTableNumber2,1, R.id.editText1,state,text);

                ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
                if(toggleButton01.isChecked()) state=1; else state=0;
                dbHandler.updateCheckBox(databaseTableNumber3,1,R.id.toggleButton1,state,"");

                dbHandler.close();
            }
        });
    }

    @Override
    protected void onPause(){
        super.onPause();
        Log.i(TAG, "On Pause");
        sharedperefs = getSharedPreferences(preferenceName, MODE_PRIVATE);
        SharedPreferences.Editor editor =sharedperefs.edit();
        firstRunPassed=true;
        editor.putBoolean("firstRunPassed", firstRunPassed);
        editor.commit();    
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "On Resume");

        sharedperefs=getSharedPreferences(preferenceName, MODE_PRIVATE);
        firstRunPassed=sharedperefs.getBoolean("firstRunPassed", false);

        dbHandler.open();
        Log.i(TAG, "dbhandler opened");

        if(firstRunPassed){
            cBox01=new CBox(); 
            cBox01=dbHandler.getCBox(databaseTableNumber1,1);
            CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
            if(cBox01.getStatus()==1) 
                checkBox01.setChecked(true); 
            else 
                checkBox01.setChecked(false);    

            cBox02=new CBox();
            cBox02=dbHandler.getCBox(databaseTableNumber1,2);
            RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
            radioGroup01.check(cBox02.getStatus());

            cBox03=new CBox();
            cBox03=dbHandler.getCBox(databaseTableNumber2,4);
            EditText editText01=(EditText) findViewById(R.id.editText1);
            editText01.setText(cBox03.getText());

            cBox04=new CBox();
            cBox04=dbHandler.getCBox(databaseTableNumber3,1);
            ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
            if(cBox04.getStatus()==1) 
                toggleButton01.setChecked(true); 
            else 
                toggleButton01.setChecked(false);
        } else {
            cBox01 = new CBox();  cBox01.setId(1); cBox01.setName(R.id.checkBox1); cBox01.setStatus(0); cBox01.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox01);
            cBox02 = new CBox();  cBox02.setId(2); cBox02.setName(R.id.radioGroup1); cBox02.setStatus(0); cBox02.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox02);
            cBox03 = new CBox();  cBox03.setId(1); cBox03.setName(R.id.editText1); cBox03.setStatus(0); cBox03.setText("Start please"); dbHandler.insertCBox(databaseTableNumber2,cBox03);
            cBox04 = new CBox();  cBox04.setId(1); cBox04.setName(R.id.toggleButton1); cBox04.setStatus(0); cBox04.setText(""); dbHandler.insertCBox(databaseTableNumber3,cBox04);
        }
        dbHandler.close();
        Log.i(TAG, "dbhandler closed");
    }
}

CBox是我的最后一堂課,用於設置和獲取數據單元格:

public class CBox {

    private int id;
    private int name;
    private int Status;
    private String text;
    private String unit;

    public long getId() {
        return id;
    }

    public String getIdInString() {
        return Long.toString(id);
    }

    public int getName() {
        return name;
    }

    public int getStatus() {
        return Status;
    }

    public String getText() {
        return text;
    }

    public String getUnit() {
        return unit;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(int name) {
        this.name = name;
    }

    public void setStatus(int status) {
        this.Status = status;
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }
}

我終於做到了。 :DI並不是問題所在,但是通過如下更改DatabaseHelperDatabase Helper類,並將該類中使用的函數的輸入變量更改為string,問題得以解決。

這是DatabaseHelper類:

public class DatabaseHelper extends SQLiteOpenHelper {

    private final String TAG = "DatabaseHelper";
    private static final String DATABASE_NAME = "database"; 
    private static final int DATABASE_VERSION = 1;

    private static final String COLUMN_ID      = "_id";
    private static final String COLUMN_NAME    = "name";
    private static final String COLUMN_VALUE   = "value";
    private static final String COLUMN_VALUE2  = "value2";

    private static final String TABLE_NAME_1     = "table1db";
    private static final String CREATE_TABLE_1   = "CREATE TABLE " + TABLE_NAME_1 + " (" + 
        COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
        COLUMN_NAME + " INTEGER," +
        COLUMN_VALUE + " INTEGER," +
        COLUMN_VALUE2 + " TEXT" +
        ");";


    private static final String TABLE_NAME_2    = "table2db";
    private static final String CREATE_TABLE_2  = "CREATE TABLE " + TABLE_NAME_2 + " (" + 
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COLUMN_NAME + " INTEGER," +
            COLUMN_VALUE + " INTEGER," +
            COLUMN_VALUE2 + " TEXT" +
            ");";


    private static final String TABLE_NAME_3   = "table3db";
    private static final String CREATE_TABLE_3   = "CREATE TABLE " + TABLE_NAME_3 + " (" + 
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COLUMN_NAME + " INTEGER," +
            COLUMN_VALUE + " INTEGER," +
                COLUMN_VALUE2 + " TEXT" +
            ");";



    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_TABLE_1); Log.i(TAG, "Table 1 created.");
        db.execSQL(CREATE_TABLE_2); Log.i(TAG, "Table 2 created.");
        db.execSQL(CREATE_TABLE_3); Log.i(TAG, "Table 3 created.");

    }

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.i(TAG, "Object created.");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        newVersion=oldVersion+1;
        Log.w(TAG, "Upgrading database from version " + oldVersion 
                + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_1 + ";");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");
        onCreate(db);
    }

    public String getTableName(String tableNumber) {

        return tableNumber;
    }

    public String getRowIdName(String tableNumber) {

        return COLUMN_ID;
    }
}

Database Handler類:

public class DatabaseHandler {

    private final String TAG     = "DatabaseHandler";
    static final  String NAME    = "name";
    static final  String VALUE   = "value";
    static final  String VALUE2  = "value2";
    private DatabaseHelper dbHelper;
    private SQLiteDatabase database;

    public DatabaseHandler(Context context) {
        dbHelper = new DatabaseHelper(context);
        Log.i(TAG, "DatabaseHelper Object created.");
    }

    public void open() throws SQLException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    public void insertCBox(String tableNumber, CBox checkBox) {
        ContentValues cv = new ContentValues();

        cv.put(NAME,  checkBox.getName());
        cv.put(VALUE, checkBox.getStatus());
        cv.put(VALUE2, checkBox.getText());
        database.insert(dbHelper.getTableName(tableNumber), null, cv);

        Log.i(TAG, "Contact added successfully.");
    }

    public void deleteCheckBox(String tableNumber, int id) {
        database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
    }

    public void updateCheckBox(String tableNumber, int id,int name,int state, String text) {

        ContentValues cv = new ContentValues();
        cv.put(NAME,  name);
        cv.put(VALUE, state);
        cv.put(VALUE2, text);
        database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
    }


    public CBox getCBox(String tableNumber, int id){
        Log.i(TAG, "getCBOX started");
        Cursor cursor = database.query(true,dbHelper.getTableName(tableNumber), null, null, null, null, null, null, null);
        Log.i(TAG, "cursor query done");
        cursor.moveToPosition(id-1);
        Log.i(TAG, "cursor is here: "+ cursor.getPosition());
//      cursor.moveToPosition(id--);
        Log.i(TAG, "cursor moved to position successfully "+ (id-1));
        CBox CBox = cursorToContact(cursor);
        Log.i(TAG, "cursor to contact done");
        cursor.close();
        Log.i(TAG, "cursor closed");
        return CBox;
    }


    public void clearTable(String tableNumber) {
        database.delete(dbHelper.getTableName(tableNumber), null, null);
    }


    private CBox cursorToContact(Cursor cursor) {
        CBox checkBox = new CBox();
        Log.i(TAG, "cursor to contact > started");
        checkBox.setId(cursor.getInt(0));
        Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
        checkBox.setName(cursor.getInt(1));
        Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
        checkBox.setStatus(cursor.getInt(2));
        Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
        checkBox.setText(cursor.getString(3));
        Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());

        return checkBox;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM