Android,多表,SQLite数据库

时间:2015-10-17 22:49:41

标签: java android sql database sqlite

Android操作系统中的SQLite数据库存在另一个问题。 我试图用两个表创建数据库:部门和学生。 Departments表包含:dep_id,dep_name和dep_major。 学生表包含:stud_id,dep_id,名字,姓氏,电子邮件,电话。

如何将数据放入这两个表?

有一个Databasehandler.java:

public class DatabaseHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;
private static final String TAG = "DatabaseHandler";
private static final String DATABASE_NAME = "studentsManager2.db";

// pola tabeli "wydzial"
private static final String TABLE_DEPARTMENTS = "departments",
        KEY_DEP_ID = "id",
        KEY_DEPARTMENT = "wydzial",
        KEY_SPECIALIZATION = "kierunek";
// pola tabeli "students"
private static final String TABLE_STUDENTS = "students",
        KEY_STUD_ID = "id",
        KEY_ID = KEY_DEP_ID,
        KEY_FIRSTNAME = "imie",
        KEY_SURNAME = "nazwisko",
        KEY_INDEKS = "indeks",
        KEY_EMAIL = "email",
        KEY_NUMER = "numer";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_DEPARTMENTS + "(" + KEY_DEP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_DEPARTMENT + " TEXT NOT NULL," + KEY_SPECIALIZATION + " TEXT NOT NULL)");
    db.execSQL("CREATE TABLE " + TABLE_STUDENTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT NOT NULL," + KEY_SURNAME + " TEXT NOT NULL," + KEY_INDEKS + " INTEGER," + KEY_EMAIL + " TEXT NOT NULL," + KEY_NUMER + " TEXT NOT NULL)");
}

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

1 个答案:

答案 0 :(得分:0)

下面的方法将使用Datbase helper class:

在sqlite数据库中插入记录
public void insertDataInBothTables() {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues valuesForDepartmentTable = new ContentValues();
    valuesForDepartmentTable.put(KEY_DEPARTMENT , "name");
    valuesForDepartmentTable.put(KEY_SPECIALIZATION , "special");

    // insert row
    long idOfDepart = db.insert(TABLE_DEPARTMENTS, null, valuesForDepartmentTable);

    ContentValues values = new ContentValues();
    values.put(KEY_FIRSTNAME, "first-name");
    values.put(KEY_SURNAME, "sur-name");
    values.put(KEY_INDEKS , "inserting-data");
    values.put(KEY_EMAIL , "inserting-data");
    values.put(KEY_NUMER , "inserting-data");
    //Parameter to add department id
    values.put(KEY_WYDZIAL, idOfDepart + "");

    // insert row
    db.insert(TABLE_STUDENTS, null, values);

}