首页 > 解决方案 > 子表外键自动填充与父表主键相同的值

问题描述

我在表中创建了两个表,其中一个主键和一个外键。我想编写当我插入table1然后再插入table2时的代码,因此table2外键列中引用table1主键的值将自动插入与表1的主键相同。

我在 android studio 中为我的 android 应用程序创建这些表和数据库,并使用 sqlite3。

CREATE TABLE table1(
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    name VARCHAR, 
    fathername VARCHAR,
    dob DATE, 
    age INT 
);

CREATE TABLE table2(
    m_id INTEGER PRIMARY KEY AUTOINCREMENT, 
    treatdate DATE, 
    hospital VARCHAR,
    city VARCHAR, 
    id2 INT,
    FOREIGN KEY (id2) REFERENCES table1(id) 
);

标签: androidsqlsqlite

解决方案


如果您使用 SQLiteDatabse插入方法,它将返回插入行上的rowid(对于未使用 WITHOUT ROWID 定义的表)。由于您使用 INTEGER PRIMARY KEY 定义id列,它是rowid列的别名,因此将返回分配给id的值(如果该列成功插入,则返回 -1 )。

例如

ContentValues cv = new ContentValues();
cv.put("name","Fred");
cv.put("fathername","George");
cv.put("dob","2000-01-01");
cv.put("age",21)
long returned_id = your_sqlite_database.insert("table1",null,cv);

returned_id将是插入table1的行的 id 。

通常,上述内容将在一个方法中,该方法将 name、fathername、dob 和 age 作为参数并返回 id。

工作示例

数据库助手(SQLiteOpenHelper 的子类) DBHelper.java

这将创建数据库和表并定义 3 种方法:-

  • addTable1Row向 table1 添加一行,该行返回一个带有插入行 ID 的 long。
  • addTable2Row向 table2 添加一行,返回一个 long 和插入行的 id
  • getAllFromTable1JoinedWithTable2就像方法名称所暗示的那样

  • 注意SQLiteOpenHelper 的 onConfigure 方法被覆盖以打开外键支持(默认情况下不打开)

:-

public class DBHelper extends SQLiteOpenHelper {

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

    public static final String TBL_TABLE1 = "table1";
    public static final String TBL_TABLE2 = "table2";

    public static final String COL_TABLE1_ID = "id";
    public static final String COL_TABLE1_NAME = "name";
    public static final String COL_TABLE1_FATHERNAME = "fathername";
    public static final String COL_TABLE1_DOB = "dob";
    public static final String COL_TABLE1_AGE = "age";

    public static final String COL_TABLE2_ID = "m_id";
    public static final String COL_TABLE2_TREATDATE = "treatdate";
    public static final String COL_TABLE2_HOSPITAL = "hospital";
    public static final String COL_TABLE2_CITY = "city";
    public static final String COL_TABLE2_ID2 = "id2";

    SQLiteDatabase mDB;

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

    @Override
    public void onCreate(SQLiteDatabase db) {

        String table1_crtsql = "CREATE TABLE IF NOT EXISTS " + TBL_TABLE1 + "(" +
                COL_TABLE1_ID + " INTEGER PRIMARY KEY, " +
                COL_TABLE1_NAME + " TEXT, " +
                COL_TABLE1_FATHERNAME + " TEXT, " +
                COL_TABLE1_DOB + " TEXT, " +
                COL_TABLE1_AGE + " INTEGER" +
                ")";
        db.execSQL(table1_crtsql);

        String table2_crtsql = "CREATE TABLE IF NOT EXISTS " + TBL_TABLE2 + "(" +
                COL_TABLE2_ID + " INTEGER PRIMARY KEY, " +
                COL_TABLE2_TREATDATE + " TEXT, " +
                COL_TABLE2_HOSPITAL + " TEXT, " +
                COL_TABLE2_CITY + " TEXT, " +
                COL_TABLE2_ID2 + " INTEGER REFERENCES " + TBL_TABLE1 + "(" + COL_TABLE1_ID + ")" +
                ")";
        db.execSQL(table2_crtsql);
    }

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

    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        db.setForeignKeyConstraintsEnabled(true);
    }

    public long addTable1Row(String name, String fathername, String dob, int age) {
        ContentValues cv = new ContentValues();
        cv.put(COL_TABLE1_NAME,name);
        cv.put(COL_TABLE1_FATHERNAME,fathername);
        cv.put(COL_TABLE1_DOB,dob);
        cv.put(COL_TABLE1_AGE,age);
        return mDB.insert(TBL_TABLE1,null,cv);
    }

    public long addTable2Row(String treatdate, String hospital, String city, long table1_reference) {
        ContentValues cv = new ContentValues();
        cv.put(COL_TABLE2_TREATDATE,treatdate);
        cv.put(COL_TABLE2_HOSPITAL,hospital);
        cv.put(COL_TABLE2_CITY,city);
        cv.put(COL_TABLE2_ID2,table1_reference);
        return mDB.insert(TBL_TABLE2,null,cv);
    }

    public Cursor getAllFromTable1JoinedWithTable2() {
        String tables = TBL_TABLE1 +
                " JOIN " + TBL_TABLE2 +
                " ON " +
                TBL_TABLE2 + "." + COL_TABLE2_ID2 +
                " = " +
                TBL_TABLE1 + "." + COL_TABLE1_ID;
        return mDB.query(tables,null,null,null,null,null,null);
    }
}
  • 注意 AUTOINCREMENT 没有被使用,因为它是不必要的,定义的列类型,而不是派生的列类型已经被使用(不是说它有任何影响)

MainActivity.java

这将实例化一个 DBHelper 对象,然后使用可用的方法将一些行添加到每个表中。2 行添加到表 1,3 行添加到表 2(弗雷德有 2 次医院就诊)。

然后根据table2和table1之间的关系提取数据,因此提取了3行。这些被转储到系统日志中。

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);

        //Add Fred
        long parentid = mDBhlpr.addTable1Row("Fred","George","2000-01-01",19);
        // Add a hospital visit for Fred
        mDBhlpr.addTable2Row("2019-01-01","Prince Fred","Timbukto",parentid);

        //Add Mary and a hospital visit all in one go
        mDBhlpr.addTable2Row("2019-01-02","St Barts","Springfield",
                mDBhlpr.addTable1Row("Mary","Tom","1999-12-23",19)
        );

        // Another hospital visit for Fred
        mDBhlpr.addTable2Row("2019-01-03","John Radcliffe","Oxford",parentid);

        // Get the joined data and dump it to the log
        Cursor csr = mDBhlpr.getAllFromTable1JoinedWithTable2();
        DatabaseUtils.dumpCursor(csr);
    }
}

结果

日志包括:-

 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@3fd1bbe9
 I/System.out: 0 {
 I/System.out:    id=1
 I/System.out:    name=Fred
 I/System.out:    fathername=George
 I/System.out:    dob=2000-01-01
 I/System.out:    age=19
 I/System.out:    m_id=1
 I/System.out:    treatdate=2019-01-01
 I/System.out:    hospital=Prince Fred
 I/System.out:    city=Timbukto
 I/System.out:    id2=1
 I/System.out: }
 I/System.out: 1 {
 I/System.out:    id=2
 I/System.out:    name=Mary
 I/System.out:    fathername=Tom
 I/System.out:    dob=1999-12-23
 I/System.out:    age=19
 I/System.out:    m_id=2
 I/System.out:    treatdate=2019-01-02
 I/System.out:    hospital=St Barts
 I/System.out:    city=Springfield
 I/System.out:    id2=2
 I/System.out: }
 I/System.out: 2 {
 I/System.out:    id=1
 I/System.out:    name=Fred
 I/System.out:    fathername=George
 I/System.out:    dob=2000-01-01
 I/System.out:    age=19
 I/System.out:    m_id=3
 I/System.out:    treatdate=2019-01-03
 I/System.out:    hospital=John Radcliffe
 I/System.out:    city=Oxford
 I/System.out:    id2=1
 I/System.out: }
 I/System.out: <<<<<

推荐阅读