带外键和模型的SQLite Android Studio CRUD

时间:2018-08-31 12:56:39

标签: android sqlite foreign-keys crud

抱歉,我的英语水平

我将建立一个简单的示例:


表T_User

id_user integer primary key autoincrement,

email_user text not null,

pass_user text not null,

id_person integer foreign key(id_person) references T_Person(id_person)

表T_Person

id_person integer primary key autoincrement,

name_person text not null,

cel_person text not null

Android Studio:

User.java

public static final String TAG = User.class.getSimpleName();

1)在这里,我需要输入表的相同名称?

public static final String TABLE = "T_User"; 

2)在这里,我需要放置表格的所有列吗?就像“ id_user”

public static final int KEY_ID_USER = "id_user";
public static final String KEY_EMAIL_USER = "email_user";
public static final String KEY_PASS_USER= "pass_user";
public static final int KEY_ID_PERSON = "id_person";

private int id;
private String email;
private String pass;
private Person person;
//constructor
//getters & setters

UserRepo.java

    public static String createTable(){
        return "CREATE TABLE " + User.TABLE  + "("
                + User.KEY_ID_USER + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + User.KEY_EMAIL_USER + " TEXT,"
                + User.KEY_PASS_USER + " TEXT,"
                + User.KEY_ID_PERSON  + " INTEGER)";
    }
    public void insert(User user) {
        SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
        ContentValues values = new ContentValues();

3)我不需要此行吗? (由于自动递增)

        values.put(User.KEY_ID_USER, user.getId());


        values.put(User.KEY_EMAIL_USER, user.getEmail());
        values.put(User.KEY_PASS_USER, user.getPass());

4)就像这样,我要从人那里获得ID?

        values.put(User.KEY_ID_PERSON , user.person.getId());


        db.insert(User.TABLE, null, values);
        DatabaseManager.getInstance().closeDatabase();
    }

5)我该如何进行更新和选择

1 个答案:

答案 0 :(得分:0)

这是一个基于您的设计的具有更新和选择方法的工作示例。

这由2个Java类,调用活动 MainActivity.java 和通常称为DBHelper的SQLiteOpenHelper类的子类组成,因此它是 DBHelper.java < / p>

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {

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

    public static final String TB_USER = "T_User";
    public static final String TB_PERSON = "T_Person";

    public static final String COl_USER_ID = BaseColumns._ID;
    public static final String COl_USER_EMAIL = "email_user";
    public static final String COL_USER_PASS = "pass_user";
    public static final String COl_USER_PERSON = "id_person";

    public static final String COL_PERSON_ID = BaseColumns._ID;
    public static final String COl_PERSON_NAME = "name_person";
    public static final String COL_PERSON_CEL = "cel_person";

    SQLiteDatabase mDB;
    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB  = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtpersonsql = "CREATE TABLE IF NOT EXISTS " + TB_PERSON + "(" +
                COL_PERSON_ID + " INTEGER PRIMARY KEY, " +
                COl_PERSON_NAME + " TEXT NOT NULL," +
                COL_PERSON_CEL + " TEXT NOT NULL " +
                ")";
        String crtusersql = "CREATE TABLE If NOT EXISTS " + TB_USER + "(" +
                COl_USER_ID + " INTEGER PRIMARY KEY, " +
                COl_USER_EMAIL + " TEXT NOT NULL, " + //perhaps make unique
                COL_USER_PASS + " TEXT NOT NULL, " +
                COl_USER_PERSON + " INTEGER REFERENCES " + TB_PERSON + "(" +
                COL_PERSON_ID +
                ")" +
                ")";
        db.execSQL(crtpersonsql);
        db.execSQL(crtusersql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    public long insertPerson(String name, String cel) {
        ContentValues cv = new ContentValues();
        cv.put(COl_PERSON_NAME,name);
        cv.put(COL_PERSON_CEL,cel);
        return mDB.insert(TB_PERSON,null,cv);
    }

    public long insertUser(String email, String pass, long personid) {
        ContentValues cv = new ContentValues();
        cv.put(COl_USER_EMAIL,email);
        cv.put(COL_USER_PASS,pass);
        cv.put(COl_USER_PERSON,personid);
        return mDB.insert(TB_USER,null,cv);
    }

    public Cursor getAllPersons() {
        return mDB.query(TB_PERSON,null,null,null,null,null,null);
    }

    public Cursor getAllUsers() {
        return mDB.query(TB_USER,null,null,null,null,null,null);
    }

    public Cursor getAllPersonsAndTheReferencedUser() {
        String table = TB_PERSON +
                " JOIN " + TB_USER +
                " ON " + COl_USER_PERSON + "=" +
                TB_PERSON + "." + COL_PERSON_ID;
        String[] columns = new String[]{
                TB_PERSON + "." + COL_PERSON_ID + " AS " + TB_PERSON + "_" + COL_PERSON_ID,
                COl_PERSON_NAME,
                COL_PERSON_CEL,
                TB_USER + "." + COl_USER_ID + " AS " + TB_USER + "_" + COl_USER_ID,
                COl_USER_EMAIL,
                COL_USER_PASS
        };
        Log.d("GETALLPandU","Table (FROM) clause = " + table);
        return mDB.query(table,columns,null,null,null,null,null);
    }

    public int changePersonsName(long personid, String newname) {
        ContentValues cv = new ContentValues();
        cv.put(COl_PERSON_NAME,newname);
        String whereclause = COL_PERSON_ID + "=?";
        String[] whereargs = new String[]{String.valueOf(personid)};
        return mDB.update(TB_PERSON,cv,whereclause,whereargs);
    }

    public int changePersonsCel(long personid, String newcel) {
        ContentValues cv = new ContentValues();
        cv.put(COL_PERSON_CEL,newcel);
        String whereclause = COL_PERSON_ID + "=?";
        String[] whereargs = new String[]{String.valueOf(personid)};
        return mDB.update(TB_PERSON,cv,whereclause,whereargs);
    }
}
  • 方法 insertPerson 用于向 T_Person 表中添加一行。
  • 方法 insertUser 用于在 T_User 表中添加一行,并指出personid(第3个参数)必须引用一个Person。
  • 方法 getAllPersons T_Person 表中获取所有行。
  • 方法 getAllUsers T_User 表中获取所有行。
  • 方法 getAllPersonsAndTheReferencedUser 根据外键/引用从“个人”和“用户”表中获取所有行。
  • 方法 changePersonsName 允许根据人员的 id 来更新人员的名称
  • 方法 changePersonscel 允许根据人员的 id 更新人员的 cel

MainActivity.java

public class MainActivity extends AppCompatActivity {

    DBHelper mDBHlpr;

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

        mDBHlpr = new DBHelper(this);

        // Delete all rows from both tables (if any)
        mDBHlpr.getWritableDatabase().delete(DBHelper.TB_USER,null,null);
        mDBHlpr.getWritableDatabase().delete(DBHelper.TB_PERSON,null,null);

        // Add some person rows
        mDBHlpr.insertPerson("Fred","0000-000-000"); // id will virtually certainly be 1
        mDBHlpr.insertPerson("Bert", "1111-111-111"); // id likely 2
        mDBHlpr.insertPerson("Mary","2222-222-222"); // id likely 3

        // Add some user rows
        mDBHlpr.insertUser("Fred@email.moc","Fred1234567890",1);
        mDBHlpr.insertUser("Bert@email.moc","Bert1234567890",2);
        mDBHlpr.insertUser("Mary@email.moc","Mary1234567890",3);

        //ooops add some unanticipated rows
        mDBHlpr.insertUser("whoever@email.moc","xxxx",3);
        mDBHlpr.insertUser("whoever@email.moc","xxxx",3);

        // Make some changes (updates)
        mDBHlpr.changePersonsCel(3,"6666-666-66");
        mDBHlpr.changePersonsName(3,"Marian");

        // get some data
        Cursor crs1 = mDBHlpr.getAllPersons();
        Cursor csr2 = mDBHlpr.getAllUsers();
        Cursor csr3 = mDBHlpr.getAllPersonsAndTheReferencedUser();

        // Output the retrieved data
        DatabaseUtils.dumpCursor(crs1);
        DatabaseUtils.dumpCursor(csr2);
        DatabaseUtils.dumpCursor(csr3);

        // Close the Cursors (should always be done when finished with the Cursor)
        crs1.close();
        crs1.close();
        csr3.close();
    }
}

这将调用DBHelper中的方法。

  • 首先实例化DBHelper的实例(mDBHlpr)。
  • 接下来,从两个表中删除所有行(如果有的话)(这样做是为了使应用程序的结果一致)。
  • 接下来添加一些Persons,然后添加用户(包括一些意外/意外用户( 结果是Person 3被3个用户引用 ))。
  • 然后进行一些更改(Mary更改为Marian,Mary(nor Marian's)cel从2222-222-222更改为6666-666-66)。
  • 所有三种选择方法(getAll ....)均已运行,并创建了3个游标。
  • 将游标转储(写入日志)。
  • 光标已关闭。

3个输出是:-

Person表(3行):-

>>>>> Dumping cursor android.database.sqlite.SQLiteCursor@a98de41
09-01 21:48:52.535 1919-1919/so52115977.so52115977 I/System.out: 0 {
       _id=1
09-01 21:48:52.536 1919-1919/so52115977.so52115977 I/System.out:    name_person=Fred
       cel_person=0000-000-000
    }
    1 {
       _id=2
       name_person=Bert
       cel_person=1111-111-111
    }
    2 {
       _id=3
       name_person=Marian
       cel_person=6666-666-66
    }
<<<<<

User表(5行)

    >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@e149fe6
    0 {
       _id=1
       email_user=Fred@email.moc
       pass_user=Fred1234567890
       id_person=1
    }
    1 {
       _id=2
       email_user=Bert@email.moc
       pass_user=Bert1234567890
       id_person=2
    }
    2 {
       _id=3
       email_user=Mary@email.moc
       pass_user=Mary1234567890
09-01 21:48:52.537 1919-1919/so52115977.so52115977 I/System.out:    id_person=3
    }
    3 {
       _id=4
       email_user=whoever@email.moc
       pass_user=xxxx
       id_person=3
    }
    4 {
       _id=5
       email_user=whoever@email.moc
       pass_user=xxxx
       id_person=3
    }
    <<<<<

链接/引用/联接(外键)人员/用户表(5行)

    >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@9645927
    0 {
       T_Person__id=1
       name_person=Fred
       cel_person=0000-000-000
       T_User__id=1
       email_user=Fred@email.moc
       pass_user=Fred1234567890
    }
    1 {
       T_Person__id=2
       name_person=Bert
       cel_person=1111-111-111
       T_User__id=2
       email_user=Bert@email.moc
       pass_user=Bert1234567890
    }
    2 {
       T_Person__id=3
       name_person=Marian
       cel_person=6666-666-66
       T_User__id=3
       email_user=Mary@email.moc
       pass_user=Mary1234567890
    }
    3 {
       T_Person__id=3
       name_person=Marian
       cel_person=6666-666-66
       T_User__id=4
       email_user=whoever@email.moc
       pass_user=xxxx
    }
    4 {
       T_Person__id=3
09-01 21:48:52.538 1919-1919/so52115977.so52115977 I/System.out:    name_person=Marian
       cel_person=6666-666-66
       T_User__id=5
       email_user=whoever@email.moc
       pass_user=xxxx
    }
    <<<<<

-注意 AUTOINCREMENT 尚未使用。

  • 在SQLite中实际上并不是AUTOINCREMENT会导致生成唯一的通常递增的数字。
  • 指定INTEGER PRIMARY KEY通常就足够了,不会产生很少需要的AUTOINCREMENT SQLite Autoincrement
  • 的开销。
  • 实际上,除非指定了WITHOUT ROWID,否则SQLite表具有一个特殊的通常隐藏的列,称为 rowid ,该列为64位有符号整数,最初将为1,然后可能为2。等等。INTEGER PRIMARY KEY编码使该列成为 rowid 列的别名(只有在编码了INTEGER PRIMARY KEY的情况下,才可以编码AUTOTOINCREMENT)。