使用外键填充SQLite数据库表



我目前正在尝试使用Android Studio填充我的SQLite数据库。到目前为止,我可以填充书桌,但不确定为什么我不能填充我的分会表。如果我去查看我的章节表,我没有输出。

据我所知,这是由于此表中使用的外键。

在我的on创作方法中,我对外键做了错误的事情?

以下是我的代码。

助手类

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "formularyApp.db";
public static final int DB_VERSION = 1;
public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DB_VERSION);
}
//when called creates query
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    String sqlBook = "CREATE TABLE book(id INTEGER PRIMARY KEY AUTOINCREMENT, bookName VARCHAR, bookAuthor VARCHAR);";
    String sqlChapter = "CREATE TABLE chapter(id INTEGER PRIMARY KEY AUTOINCREMENT, chapterName VARCHAR, book_id INTEGER, FOREIGN KEY(book_id) REFERENCES book(id))";

    sqLiteDatabase.execSQL(sqlBook);
    sqLiteDatabase.execSQL(sqlChapter);

}

public boolean addChapter(String chapterName, Integer book_id){
    SQLiteDatabase db = getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("chapterName", chapterName);
    contentValues.put("bookID", book_id);
    db.insert("chapter", null, contentValues);
    db.close();
    return true;
}
public boolean addBook(String bookName, String bookAuthor){
    SQLiteDatabase db = getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("bookName", bookName);
    contentValues.put("bookAuthor", bookAuthor);
    db.insert("book", null, contentValues);
    db.close();
    return true;
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    String sqlBook = "DROP TABLE IF EXISTS book";
    String sqlChapter = "DROP TABLE IF EXISTS chapter";
    sqLiteDatabase.execSQL(sqlBook);
    sqLiteDatabase.execSQL(sqlChapter);
    onCreate(sqLiteDatabase);
}
}

主要活动

public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
DatabaseHelper db;
/** Called when the activity is created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = new DatabaseHelper(this);
    db.addBook("Tester Book 5", "Test author");
    db.addChapter("The basics", 5);
    Toast.makeText(this, "updated", Toast.LENGTH_SHORT).show();
    viewPager = findViewById(R.id.viewPager);
    IntroAdapter adapter = new IntroAdapter(getSupportFragmentManager());
    viewPager.setAdapter(adapter);
}

在您的AddChapter方法中您有一个错字:

contentValues.put("bookID", book_id);

应该是

contentValues.put("book_id", book_id);

您使用的是错误的列名

最新更新