2015-06-17 1 views
0
I am trying to make database table using primary key and foreign key. My first table `Categ` contains fields `catgoryId` as primary key and second table `Pers` contains `categoryId` as foreign key. 

Первое создание таблицы работает нормально, а второе дает ошибку, не в состоянии вставить данные в таблицу Person.Ошибка при создании таблицы базы данных на Android с использованием SQL

Кодекс:

public void onCreate(SQLiteDatabase db) { 
     // if any table missing then recreate all tables (can be done    dynamically) 
     if(!isTableExist(db, categ)||!isTableExist(db, pers)){ 

     db.execSQL("DROP TABLE IF EXISTS "+categ); 
     db.execSQL("DROP TABLE IF EXISTS "+pers); 

     db.execSQL("create table "+categ+"(categoryId INTEGER PRIMARY KEY autoincrement, name text, isApproved integer ,isDeleted integer, createdDate  text, modifiedDate text)"); 

     db.execSQL("create table "+pers+" (personId INTEGER PRIMARY KEY autoincrement, name text, photo text, biography text,categoryId  integer,isApproved integer, isDeleted integer, createdDate text, modifiedDate  text,FOREIGN KEY(categoryId) REFERENCES categ(categId))"); 
     } 
    } 

} 

Я создал таблицу с помощью вызова метода updateAllTables. UpdateAllTables определяется следующим образом:

public boolean updateAllTables(Context context){ 
    onCreate(this.getReadableDatabase()); 
    CDataTransition datatransition = new CDataTransition(context); 
    JSONObject jObj = datatransition.getAllTables(); 
    try { 
     JSONArray category = jObj.getJSONArray("categories"); 
     insertCategories(category); 

     JSONArray person = jObj.getJSONArray("persons"); 
     insertPersons(person); 
     return true; 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }  
    return false; 
} 

Методы, используемые выше (insertCategoriers и insertPerson) определены таким образом:

public void insertCategories(JSONArray jsArr){ 
    for (int i = 0; i < jsArr.length(); i++) { 
     try { 
      JSONObject category = jsArr.getJSONObject(i); 
      ContentValues cv = new ContentValues(); 
        cv.put("categoryId",Integer.parseInt(category.getString("categoryId"))); 
      cv.put("name",category.getString("name")); 
      cv.put("isApproved",Integer.parseInt(category.getString("isApproved"))); 
      cv.put("isDeleted",Integer.parseInt(category.getString("isDeleted"))); 
      cv.put("createdDate",category.getString("createdDate")); 
      cv.put("modifiedDate",category.getString("modifiedDate")); 

      insertData(categ, cv); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }   
    } 
} 

public void insertPersons(JSONArray jsArr){ 
    for (int i = 0; i < jsArr.length(); i++) { 
     try { 
      JSONObject person = jsArr.getJSONObject(i); 
      ContentValues cv = new ContentValues(); 
      cv.put("personId",Integer.parseInt(person.getString("personId"))); 
      cv.put("name",person.getString("name")); 
      cv.put("photo",person.getString("photo")); 
      cv.put("biography",person.getString("biography")); 
      cv.put("categoryId",Integer.parseInt(person.getString("categoryId"))); 
      cv.put("isApproved",Integer.parseInt(person.getString("isApproved"))); 
       cv.put("isDeleted",Integer.parseInt(person.getString("isDeleted"))); 
      cv.put("createdDate",person.getString("createdDate")); 
      cv.put("modifiedDate",person.getString("modifiedDate")); 

      insertData(pers, cv); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }   
    } 
} 
+0

Я не вижу никакой вставки в вашем примере кода только падение и создавать операторы таблицы – Alexander

ответ

0

Внешний ключ является неправильным:

дб .execSQL ("create table" + categ + "(categoryId INTEGER PRIMARY KEY автоинкремент, текст имени, isApproved integer, isDeleted integer, createdDate text, modifiedDate text)");

db.execSQL ("создать таблицу "+ перс +"(PersonId INTEGER PRIMARY KEY автоинкремент, название текста, фото текст, биография текст, CategoryId целое, isApproved целое, IsDeleted целое, createdDate текст, ModifiedDate текст, FOREIGN KEY (CategoryId) ССЫЛКИ categ (categId)) ");

Изменить его

FOREIGN KEY(categoryId) REFERENCES categ(categoryId))