我正在創建兩個表,一個用於書籍,另一個用於stores.I想要通過給Store_ID將BookStore表中的每本書鏈接到StoreTable。 Store_Id將成爲StoreTable中的主鍵。我在外鍵的語法方面遇到了問題。我還檢查了http://www.sqlite.org/foreignkeys.html以供參考,但這並沒有給我足夠的解釋。如果有人幫助我,我將非常感激。SQLite中的外鍵
public class DatabaseHelper extends SQLiteOpenHelper{
//Name of databases
public static final String DATABASE_NAME = "Library.db";
//Version of database
public static final int DATABASE_VERSION = 1;
//Table of Stores
public static final String STORE_TABLE = "Store_Table";
public static final String STORE_ID = "Store_ID";
public static final String STORE_NAME = "Store_name";
public static final String STORE_Address = "Store_Address";
public static final String STORE_LAT = "lat";
public static final String STORE_LNG = "lng";
//Table of Books
public static final String BOOKS_TABLE = "Books_Table";
public static final String BOOK_ID = "Book_ID";
public static final String BOOK_NAME = "Book_name";
public static final String BOOK_AUTHOR = "Book_Author";
public static final String BOOKStore = "BookStore_ID";
//Creating Stores Table
private static final String SQL_CREATE_TABLE_STORE = "CREATE TABLE " + STORE_TABLE + "("
+ STORE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ STORE_NAME + " TEXT NOT NULL, "
+ STORE_Address + " TEXT NOT NULL, "
+ STORE_LAT + " TEXT NOT NULL, "
+ STORE_LNG + " TEXT NOT NULL"
+");";
//Creating Books Table
private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
+ BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BOOK_NAME + " TEXT NOT NULL, "
+ BOOK_AUTHOR + " TEXT NOT NULL, "
//How to relate BookStore with Store_ID here?
+FOREIGN KEY(BOOKStore) REFERENCES STORE_TABLE(STORE_ID));
+");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_STORE);
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_BOOKS);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//Clear all data
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + STORE_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + BOOKS_TABLE);
//RECREAT THE TABLES
onCreate(sqLiteDatabase);
}
}
它說,在每一個變量和每一個關鍵字「無法解析符號」。 –
然後你的Java代碼有問題。這個原始的SQL語句應該沒有錯誤地運行。 –
這並沒有顯示任何錯誤 ' (私有靜態最後絃樂SQL_CREATE_TABLE_BOOKS = 「CREATE TABLE」 + BOOKS_TABLE + 「(Book_ID INTEGER PRIMARY KEY AUTOINCREMENT,BOOK_NAME TEXT,BOOK_AUTHOR的文本,BookStore_ID整數),約束fk_bookstore外鍵(BookStore_ID )\ n「+ 」REFERENCES Store_Table(Store_ID)「;) ' –