2015-06-21 59 views
0

如果運行時,我的應用程序保持代碼行db.execSQL(createOrderTable);db.execSQL(createOrderDetail);(它們使用外鍵創建兩個表),請刪除應用程序運行OK。無法在sqlite中使用外鍵創建表

這是我對onCreate()方法:

String createUserTable = "create table " + USER_TABLE + 
      "(userID INTEGER PRIMARY KEY AUTOINCREMENT," + 
      "userName TEXT NOT NULL," + 
      "phoneNumber INTEGER);"; 
    String createProductTable = "create table " + PRODUCT_TABLE + 
      "(productID INTEGER PRIMARY KEY AUTOINCREMENT," + 
      "department TEXT,"+ 
      "name TEXT," + 
      "price REAL," + 
      "status NUMERIC);"; 
    String createOrderTable = "create table " + ORDER_TABLE + 
      "(orderID INTEGER PRIMARY KEY AUTOINCREMENT," + 
      "FOREIGN KEY(userID) REFERENCES User(userID)," + 
      "FOREIGN KEY(productID) REFERENCES Product(productID));"; 
    String createOrderDetail = "create table " + ORDER_DETAIL_TABLE + 
      "(FOREIGN KEY(orderID) REFERENCES Order(orderID)," + 
      "customerName TEXT," + 
      "address TEXT," + 
      "totalPrice REAL," + 
      "quantity INTEGER);"; 
    db.execSQL(createUserTable); 
    db.execSQL(createProductTable); 
    db.execSQL(createOrderTable); 
    db.execSQL(createOrderDetail); 

這是我爲onUpgrade()

db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE); 
    db.execSQL("DROP TABLE IF EXISTS " + PRODUCT_TABLE); 
    db.execSQL("DROP TABLE IF EXISTS " + ORDER_TABLE); 
    db.execSQL("DROP TABLE IF EXISTS " + ORDER_DETAIL_TABLE); 
    onCreate(db); 

如何我現在可以創建其他兩個表?任何人都可以幫忙感謝!

+2

是否有錯誤訊息? –

+0

'AdbCommandRejectedException獲取設備模擬器-5554的屬性:設備脫機'我得到這個,但我不知道它是否與數據庫相關聯 –

回答

0

您沒有在createOrderTable查詢中創建列userId和productId,但試圖創建外鍵引用。首先創建一個列,然後引用它。

如:

String createOrderTable = "create table " + ORDER_TABLE + 
     "(orderID INTEGER PRIMARY KEY AUTOINCREMENT," + 
     "userID INTEGER,"+ 
     "productID INTEGER,"+ 
     "FOREIGN KEY(userID) REFERENCES User(userID)," + 
     "FOREIGN KEY(productID) REFERENCES Product(productID));"; 
String createOrderDetail = "create table " + ORDER_DETAIL_TABLE + 
     "(orderID INTEGER,"+ 
     "customerName TEXT," + 
     "address TEXT," + 
     "totalPrice REAL," + 
     "quantity INTEGER," + 
     "FOREIGN KEY(orderID) REFERENCES Order(orderID));"; 
+0

它仍然在創建訂單表查詢時出現語法錯誤。我嘗試使用db.execSQL(「PRAGMA foreign_keys = ON;」)啓用外鍵支持;'但沒有結果 –

0

你必須定義你的用戶ID和ProductID列,然後設置就可以了外鍵。

String createOrderTable = "create table " + ORDER_TABLE + 
     "(orderID INTEGER PRIMARY KEY AUTOINCREMENT," + 
     " userID integer," + 
     "FOREIGN KEY(userID) REFERENCES User(userID)," + 
     "productID integer" 
     "FOREIGN KEY(productID) REFERENCES Product(productID));";