SQLite
 sql >> база данни >  >> RDS >> SQLite

Как да актуализирате/изтриете с елементи от две различни таблици SQLite

Никога не трябва да се налага да актуализирате няколко таблици наведнъж поне за една промяна, напр. името на ученика се е променило (таблицата на студентите ще бъде променена) или кажете променена оценка (променете съответния запис за оценка на ученика).

Така че смятам, че най-подходящите са методи за актуализиране на данните на ученика (собствено или фамилно име или и двете) и метод за промяна на оценките (отново или и двете).

Що се отнася до изтриването, можете да направите това, като изтриете последователно от таблицата с оценки и от таблицата за ученици или обратно.

Като такъв смятам, че следният код включва методи deleteStudentInfo , changeStudentName , changeStudentFirstName , changeStudentLastName и changeStudentGrade и също така включва примерно използване заедно със създаване и попълване на таблиците (може да пожелаете да разгледате преработената схема):-

public class MainActivity extends AppCompatActivity {

    public static final String DBNAME = "study";
    public static final String STUDENT_TABLE_NAME = "STUDENT_TABLE";
    public static final String COL_STUDENT_ID = "studentid";
    public static final String COL_STUDENT_FIRSTNAME = "fname";
    public static final String COL_STUDENT_LASTNAME = "lname";

    public static final String CLASS_TABLE_NAME = "CLASS_TABLE";
    public static final String COL_CLASS_ID = "classid";
    public static final String COL_CLASS_NAME = "classname";

    public static final String GRADE_TABLE_NAME = "GRADE_TABLE";
    public static final String COL_GRADE_POINTGRADE = "pointgrade";
    public static final String COL_GRADE_LETTERGRADE = "lettergrade";
    public static final String BY_STUDENTID = COL_STUDENT_ID + "=?";
    public static final String BY_CLASSID = COL_CLASS_ID + "=?";



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

        SQLiteDatabase db = openOrCreateDatabase(DBNAME,Context.MODE_PRIVATE,null);
        db.execSQL("CREATE TABLE IF NOT EXISTS " + STUDENT_TABLE_NAME + " (" +
                COL_STUDENT_ID + " TEXT PRIMARY KEY, " +
                COL_STUDENT_FIRSTNAME + " TEXT," +
                COL_STUDENT_LASTNAME + " TEXT)"
        );
        db.execSQL("CREATE TABLE IF NOT EXISTS " + CLASS_TABLE_NAME + "(" +
                 COL_CLASS_ID + " TEXT PRIMARY KEY," +
                 COL_CLASS_NAME + " TEXT UNIQUE " +
                ")"
        );
        db.execSQL("CREATE TABLE IF NOT EXISTS " + GRADE_TABLE_NAME + "(" +
                COL_STUDENT_ID + " TEXT, " +
                COL_CLASS_ID + " TEXT, " +
                COL_GRADE_POINTGRADE + " INTEGER, " +
                COL_GRADE_LETTERGRADE + " TEXT" +
                ")"
        );
        db.execSQL("INSERT OR IGNORE INTO " + STUDENT_TABLE_NAME +
                " VALUES" +
                "('00001','Fred','Smith')," +
                "('00010','Mary','Thomas')," +
                "('00910','Angela','Jones')"
        );
        db.execSQL("INSERT OR IGNORE INTO " + CLASS_TABLE_NAME +
                " VALUES" +
                "('001','English')," +
                "('101','Mathematics')," +
                "('201','Chemistry')"
        );
        db.execSQL("INSERT OR IGNORE INTO " + GRADE_TABLE_NAME +
                " VALUES" +
                "    ('00001','001',99,'A'), -- Fred Smith has 99 point grade as an A in English\n" +
                "    ('00001','101',25,'F'), -- Fred Smith has 25 point grade as an F on Mathematics\n" +
                "    ('00010','201',76,'B'), -- Angela Jones 76 a B in Chemistry\n" +
                "    ('00910','101',50,'C'), \n" +
                "    ('00910','201',63,'C'),\n" +
                "    ('00910','001',89,'A')\n" +
                ";"
        );

        changeStudentName(db,"00001","Joe","Bloggs");
        changeStudentFirstName(db,"00001","Harry");
        changeStudentLastName(db,"00001","Hoffmann");
        // e.g. won't change due to -1 (skip pointsgrade) and null (skip lettergrade)
        changeStudentGrade(db,"00001","001",-1,null);
        // Change both
        changeStudentGrade(db,"00001","001",25,"D");
        changeStudentGrade(db,"00001","001",27,null);

        // Ooops invalid student id
        if (deleteStudentInfo(db,"001")) {
            Log.d("DELETION","Student 001 deleted.");
        } else {
            Log.d("DELETION","Ooops Student 001 not deleted?????");
        }

        // Corrected Student ID
        if (deleteStudentInfo(db,"00001")) {
            Log.d("DELETION","Student 001 deleted.");
        } else {
            Log.d("DELETION","Ooops Student 001 not deleted?????");
        }
    }

    private boolean deleteStudentInfo(SQLiteDatabase db, String studentid) {

        String tag = "STUDENT_DELETE";
        String student_table = "STUDENT_TABLE";
        String grade_table = "GRADE_TABLE";

        long pre_delete_student_count = DatabaseUtils.queryNumEntries(db,student_table);
        long pre_delete_grade_count = DatabaseUtils.queryNumEntries(db,grade_table);

        String whereclause = "studentid =?";
        String[] whereargs = {studentid};

        db.delete(student_table,whereclause,whereargs);
        db.delete(grade_table,whereclause,whereargs);

        long post_delete_student_count = DatabaseUtils.queryNumEntries(db,student_table);
        long post_delete_grade_count = DatabaseUtils.queryNumEntries(db,grade_table);

        Log.d(
                tag,
                "Number of Students deleted from " +
                        student_table + " is " +
                        String.valueOf(
                                pre_delete_student_count - post_delete_student_count
                        ));
        Log.d(
                tag,
                "Number of Grades deleted from " + grade_table + " is " +
                        String.valueOf(
                                pre_delete_grade_count - post_delete_grade_count
                        )
        );
        if ((pre_delete_student_count + pre_delete_grade_count) != (post_delete_student_count + post_delete_grade_count)) {
            return true;
        }
        return false;
    }

    /**
     * Flexible Student Name Change
     *
     * @param db            The SQliteDatabase
     * @param studentid     The studentid (String)
     * @param newfirstname  The new firstname, null or blank to leave as is
     * @param newlastname   the new lastname, null or blank to leave as is
     */
    private void changeStudentName(SQLiteDatabase db, String studentid, String newfirstname, String newlastname ) {

        //Anything to do? if not do nothing
        if ((newfirstname == null || newfirstname.length() < 1) && (newlastname == null || newlastname.length() < 1)) {
            return;
        }
        ContentValues cv = new ContentValues();
        if (newfirstname != null && newfirstname.length() > 0) {
            cv.put(COL_STUDENT_FIRSTNAME,newfirstname);
        }
        if (newlastname != null && newlastname.length() > 0) {
            cv.put(COL_STUDENT_LASTNAME,newlastname);
        }
        // Overcautious check
        if (cv.size() < 1) {
            return;
        }
        db.update(STUDENT_TABLE_NAME,cv,BY_STUDENTID,new String[]{studentid});
    }

    /**
     * Change a Student's First Name (invokes changeStudentName method)
     * @param db            The SQLiteDatabase
     * @param studentid     The student's id (String)
     * @param newfirstname  The new first name to apply
     */
    private void changeStudentFirstName(SQLiteDatabase db, String studentid, String newfirstname) {
        changeStudentName(db,studentid,newfirstname,null);
    }

    /**
     * Change a Student's Last Name (invokes changeStudentName method)
     * @param db
     * @param studentid
     * @param newlastname
     */
    private void changeStudentLastName(SQLiteDatabase db, String studentid, String newlastname) {
        changeStudentName(db,studentid,null,newlastname);
    }

    /**
     * Change a students grade (allowing just one (points/letter))
     * @param db
     * @param studentid
     * @param classid
     * @param newpointsgrade
     * @param newlettergrade
     */
    private void changeStudentGrade(SQLiteDatabase db, String studentid, String classid, int newpointsgrade, String newlettergrade) {
        // Anything to do? if not do nothing
        if (newpointsgrade < 0 && (newlettergrade == null || newlettergrade.length() < 1)) {
            return;
        }
        ContentValues cv = new ContentValues();
        if (newpointsgrade >= 0) {
            cv.put(COL_GRADE_POINTGRADE,newpointsgrade);
        }
        if (newlettergrade != null && newlettergrade.length() > 0) {
            cv.put(COL_GRADE_LETTERGRADE,newlettergrade);
        }
        String whereclause = COL_STUDENT_ID + "=? AND " + COL_CLASS_ID + "=?";
        String[] whereargs = new String[]{studentid,classid};
        db.update(GRADE_TABLE_NAME,cv,whereclause,whereargs);
    }
}



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Връщане на редове, които съдържат буквено-цифрови знаци в SQLite

  2. SQLite3.Изключение:дисковото изображение на базата данни е неправилно формирано

  3. Коригиране на грешка:„Избиранията отляво и отдясно на UNION нямат същия брой колони с резултати“ в SQLite

  4. 4 начина да получите информация за структурата на таблицата в SQLite

  5. SQLite - Изберете данни