我试图在表中创建外键但是它抛出了错误
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" CREATE TABLE " + TABLE_NAME + "( "+ KEY_TEXT + " TEXT NOT NULL, " +
KEY_DATE + " TEXT NOT NULL PRIMARY KEY UNIQUE, " +
KEY_LOCATION + " TEXT , " +KEY_SMILEY+ " TEXT, "
+ KEY_IMAGE + " BLOB , " + KEY_AUDIO + " BLOB, "
+ KEY_VIDEO + " BLOB, " + KEY_ID+" INTEGER "+");"
);
db.execSQL(" CREATE TABLE " + IMAGES_TABLE + "( "+ KEY_DATE + " TEXT NOT NULL FOREIGN KEY(date) REFERENCES Diary(date) ,
"+ KEY_IMAGE + " BLOB , " + KEY_ID+ " INTEGER PRIMARY KEY "+");");
}
Logcat错误
04-02 11:04:41.699: E/SQLiteLog(24544): (1) near "FOREIGN": syntax error
04-02 11:04:41.699: D/AndroidRuntime(24544): Shutting down VM
04-02 11:04:41.699: W/dalvikvm(24544): threadid=1: thread exiting with uncaught exception (group=0x41cb82a0)
04-02 11:04:41.709: E/AndroidRuntime(24544): FATAL EXCEPTION: main
04-02 11:04:41.709: E/AndroidRuntime(24544): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abs.mydiary/com.abs.mydiary.Diary}: android.database.sqlite.SQLiteException: near "FOREIGN": syntax error (code 1): , while compiling: CREATE TABLE images( date FOREIGN KEY(date) REFERENCES Diary(date) , image BLOB , _id INTEGER PRIMARY KEY );
答案 0 :(得分:2)
试试这个,我修改了你的代码,你必须重新分配Key_date变量值作为" date1"或者" my_date" ..等因为" date"是一个关键词,你不能使用sql的关键字作为列名。
db.execSQL(" CREATE TABLE " + IMAGES_TABLE + "
( "+ KEY_DATE + " TEXT NOT NULL ,
"+ KEY_IMAGE + " BLOB ,
"+ KEY_ID+ " INTEGER PRIMARY KEY "+"
)FOREIGN KEY("+ KEY_DATE + ") REFERENCES Diary("+ KEY_DATE + ");");
答案 1 :(得分:0)
尝试这种方式:
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER,
FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);
答案 2 :(得分:0)
CREATE TABLE track(
trackid INTEGER,
trackname TEXT,
trackartist INTEGER,
FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);