簡體   English   中英

如何在 SQLite 中插入帶有 Foreign KEY 的值?

[英]How to insert values with Foreign KEY in SQLite?

我是 Android Sqlite 數據庫的新手。 我在 Android 中創建了一個帶有 SQLite 的數據庫,我有一個表Student_details使用表的外鍵: Student ,我將 id 設置為AUTOINCREMENT 我試圖從Student表中返回AUTOINCREMENT Id 的值。

但我堅持使用return values插入COLUMN_FR_KEY_USER_ID = "student_id"; 作為外鍵值。

如何使用ContentValues將另一個表的外鍵值添加到insetDataIntoStudentDetails方法中?

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "finalStudent.db";
    private static final int VERSION_NUMBER = 16;
    private static final String TABLE_STUDENT = "Student";
    private static final String TABLE_DETAILS_NAME = "Student_details";

    private static final String COLUMN_STUDENT_ID = "id";
    private static final String COLUMN_DETAILS_ID = "id";
    private static final String COLUMN_FR_KEY_USER_ID = "student_id";
    private static final String COLUMN_STUDENT_NAME = "name";
    private static final String COLUMN_DETAILS_NAME = "name";
    private static final String COLUMN_STUDENT_EMAIL = "email";
    private static final String COLUMN_STUDENT_PASSWORD = "password";

    private static final String CREATE_STUDENT_TABLE = "CREATE TABLE "+TABLE_STUDENT+"( "+COLUMN_STUDENT_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+COLUMN_STUDENT_NAME+" TEXT, "+COLUMN_STUDENT_EMAIL+" TEXT, "+COLUMN_STUDENT_PASSWORD+" TEXT)";
    private static final String CREATE_DETAILS_TABLE = "CREATE TABLE "+TABLE_DETAILS_NAME+"( "+COLUMN_DETAILS_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+COLUMN_DETAILS_NAME+" TEXT, "+COLUMN_FR_KEY_USER_ID+" INTEGER, FOREIGN KEY("+COLUMN_FR_KEY_USER_ID+") REFERENCES "+TABLE_STUDENT+" ("+COLUMN_STUDENT_ID+") ON UPDATE CASCADE ON DELETE CASCADE)";

    private Context context;
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_STUDENT;
    private static final String DROP_DETAILS_TABLE = "DROP TABLE IF EXISTS "+TABLE_DETAILS_NAME;


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION_NUMBER);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            Toast.makeText(context,"Table created successfully and called onCreate method",Toast.LENGTH_SHORT).show();
            db.execSQL(CREATE_STUDENT_TABLE);
            db.execSQL(CREATE_DETAILS_TABLE);
        }catch (Exception e){
            Toast.makeText(context,"Exception : "+e,Toast.LENGTH_SHORT).show();
        }
    }

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

            Toast.makeText(context,"Table created successfully and called onCreate method",Toast.LENGTH_SHORT).show();
            db.execSQL(DROP_TABLE);
            db.execSQL(DROP_DETAILS_TABLE);
            onCreate(db);
        }catch (Exception e){
            Toast.makeText(context,"Exception : "+e,Toast.LENGTH_SHORT).show();
        }

    }

    public long insertDataIntoStudent( String name, String email, String password){
        // to write or read data in database , we have to call getWritableDatabase
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        // we have to call contentValues class to store data in the data

        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_STUDENT_NAME,name);
        contentValues.put(COLUMN_STUDENT_EMAIL,email);
        contentValues.put(COLUMN_STUDENT_PASSWORD,password);

        // Insert the new row, returning the primary key value of the new row
        long newRowId = sqLiteDatabase.insert(TABLE_STUDENT,null,contentValues);
        return newRowId;
    }


    public void insetDataIntoStudentDetails(String name){

        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
       // TODO: insert the foreign key's value 
        contentValues.put(name,name);
    }


    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        //enable foreign key constraints like ON UPDATE CASCADE, ON DELETE CASCADE
        db.execSQL("PRAGMA foreign_keys=ON;");
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private final AppCompatActivity activity = MainActivity.this;
    DatabaseHelper databaseHelper;

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

        databaseHelper = new DatabaseHelper(activity);
        databaseHelper.insertDataIntoStudent("Bappy","abcd@gmail.com","145456");
    }
    }

我一般會回答有關數據庫的問題,而不是專門針對 Sqlite 或它在 Android 中的使用情況。

所以你有學生的名字(不是主鍵),但你需要將這個學生的一些額外數據保存到另一個表中。 步驟是:

  1. 執行SELECT id FROM students WHERE name =? 找到相關的標識符。
  2. 使用檢索到的id作為鍵為您的輔助表執行INSERT INTO student_details

額外提示:

  1. 名稱不是一個好的唯一標識符。 多一個標准是很好的——比如某個組名、組號甚至出生日期。
  2. 當您的數據庫足夠大時,您可能會受益於搜索條件的index以優化第一個查詢的執行。 但通常情況下,客戶端(應用程序內)數據庫並非如此。
  3. 這里我們假設 name 不是在搜索id和執行INSERT之間可以由其他人(或其他人)更新的數據。 否則,明智的做法是使用事務並“鎖定”你的學生,直到你完成更新。

暫無
暫無

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

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