2014-08-28 45 views
0

我是新的android開發和努力,當使用SQLite中的相鄰模型來創建一個表,但編譯失敗,此錯誤消息的Android源碼鄰接模式

| id | parentid | name | 
----------------------------------------- 
| 1 | null  | animal | 
| 2 | null  |vegetable | 
| 3 | 1   | doggie | 
| 4 | 2   | carrot | 
|  |    |   | 
|  |    |   | 

需要數據庫交互 一個項目這是我的代碼:

private static final String CREATE_TABLE_CATEGORIES="CREATE TABLE "+TABLE_CATEGORIES+"(id INTEGER PRIMARY KEY AUTOINCREMENT,"+category_name+ 
      " TEXT,parentid INTEGER ,foreign key parentid_fk(parentid) references "+TABLE_CATEGORIES+" (id));"; 

@Override 
    public void onCreate(SQLiteDatabase db){ 
     //Creation required tables 


     db.execSQL(CREATE_TABLE_CATEGORIES); 

    } 
.... 
.... 
.... 
.... 
@Override 
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){ 
     // on upgrade drop older tables 
     db.execSQL("PRAGMA foreign_keys = ON;"); 
     db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CATEGORIES); 
     // create new tables 
     onCreate(db); 
    } 

這是錯誤:

at dalvik.system.NativeStart.main(Native Method) 
    Caused by: android.database.sqlite.SQLiteException: near "parentid_fk": syntax error (code 1): , while compiling: CREATE TABLE Categories(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,parentid INTEGER ,foreign key parentid_fk(parentid) references Categories (id)); 

回答

2

爲了給出一個外鍵約束的名稱,必須使用約束關鍵字:

CONSTRAINT parentid_fk FOREIGN KEY (parentid) REFERENCES Categories(id) 

另外,不給它一個名字:

FOREIGN KEY (parentid) REFERENCES Categories(id) 
+0

謝謝我解決了這一問題:DI認爲我使用了Mysql語法。 – TheGreenGoblen 2014-08-28 13:07:17