2017-09-01 78 views
0
public void addcolumn(String year,String period){ 


    //Create column name here 

    Calendar now = Calendar.getInstance(); 
    int yeara = now.get(Calendar.YEAR); 
    int month = now.get(Calendar.MONTH) + 1; 
    int day = now.get(Calendar.DAY_OF_MONTH); 

    //select period according to current time 

    String colnew = ""+yeara+"_"+month+"_"+day+"_"+period; 
    SQLiteDatabase db = this.getWritableDatabase(); 
    String exec; 



    //Add column in table according to given year 
    // 

    if (year.equals("First Year")) { 
     exec="ALTER TABLE "+ table_name1+" ADD COLUMN "+colnew+" INTEGER NOT NULL DEFAULT 0"; 
     db.execSQL(exec); 

    } 
    else if (year.equals("Second Year")) { 
     db.execSQL("ALTER TABLE "+ table_name2+" ADD COLUMN "+colnew+" INTEGER NOT NULL DEFAULT 0"); 

    } 
    else if (year.equals("Third Year")) { 
     db.execSQL("ALTER TABLE "+ table_name3+" ADD COLUMN "+colnew+" INTEGER NOT NULL DEFAULT 0"); 

    } 
    else if (year.equals("Fourth Year")) { 
     db.execSQL("ALTER TABLE "+ table_name4+" ADD COLUMN "+colnew+" INTEGER NOT NULL DEFAULT 0"); 

    } 


} 

現有數據庫的表但當我嘗試添加使用addcolumn()方法我的應用程序崩潰列。 如果我的代碼有問題,請幫我修改它。在我的Android應用我想將列添加到使用下面的方法

+1

「我的應用程序崩潰」 - 請發佈您的LogCat輸出 – Droidman

+0

LogCat輸出? –

+0

如果我在評論後運行代碼: –

回答

1

我可以看到一個明顯的錯誤,就是你試圖改變輔助類的onUpgrade()方法外的數據庫模式。

只能在onUpgrade()方法內改變模式,類似於只能在onCreate()內創建模式。

你將不得不升級你的數據庫版本,並應該觸發你的onUpgrade()代碼。處理它的正確方法取決於視角。你可以截斷你的整個數據庫,並調用onCreate(),它現在將有改變的模式,或者你可以有與db版本匹配並改變模式的情況。

退房這個答案詳細信息:

How to add new Column to Android SQLite Database?

+0

在輔助類的onupgrade方法內使用'alter table'sqlite命令是否有必要? –

+0

任何人都可以舉例說明如何調用onupgrade()方法。 –

+0

我在回答中指定了一個鏈接。請查看onUpgrade()的示例。是的,在onCreate()或onUpgrade()中必須具有alter語句或任何DDL命令@Kushan Schemas/Database結構可以在'onUpgrade'之外更改,'onCreate'這些基本上是簡便的方法。 – Kushan

0

看來,你正試圖增加沿例如行指定的列您的ALTER陳述將會像ALTER TABLE youtablename ADD COLUMN 20170901 INTEGER NOT NULL DEFAULT 0

這將導致失敗的SQL將把這個數字爲數字而不是一個字符串,並沿的線條抱怨: -

SQLiteManager: Likely SQL syntax error: ALTER TABLE log ADD COLUMN 2020 INTEGER NOT NULL DEFAULT 0 [ near "2020": syntax error ] Exception Name: NS_ERROR_FAILURE Exception Message: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [mozIStorageConnection.createStatement] 

你說明使用ALTER TABLE log ADD COLUMN '20170901' INTEGER NOT NULL DEFAULT 0一個字符串(即封閉單引號或雙引號)。

或者,您可以使用非數字前綴,例如ALTER TABLE youtablename ADD COLUMN Y20170901 INTEGER NOT NULL DEFAULT 0(即Y是數字部分的前綴)。

+0

我可以故意從其他類調用'onupgrade()'方法嗎? –

+0

我的意思是dbhelper類的'onupgrade()'方法。 –

+0

是的,理論上,像'onUpgrade'通常用於調用'onCreate'。但是我不確定你是否想要/需要使用另一種方法/方法,那麼你會這麼稱呼它。 – MikeT

相關問題