gpt4 book ai didi

java - 使用外键填充 SQLite 数据库表

转载 作者:行者123 更新时间:2023-12-02 10:09:03 24 4
gpt4 key购买 nike

我目前正在尝试使用 Android studio 填充我的 SQLite 数据库。到目前为止,我可以填充图书表,但不确定为什么我无法填充章节表。如果我去查看我的章节表,我不会得到任何输出。

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

在我的 onCreate 方法中,我是否对外键做了错误的操作?

下面是我的代码。

助手类

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

}
}

主要 Activity

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

您使用了错误的列名称

关于java - 使用外键填充 SQLite 数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55125118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com