2015-06-18 46 views
5

我嘗試使用swift在表中添加一列。如何在SWIFT中的sqlite表中添加列

我的代碼:

connect_db(); 
    adddbfield("mynewfield","mytable"); 

func connect_db() -> Bool { 
    let sDBPath=<is correctly set>; 
    if sqlite3_open(sDBPath, &db) != SQLITE_OK { 
     println("Failed to open db") 
     return false; 
    }else{ 
     return true; 
    } 
} 

func adddbfield(sFieldName:String, sTable:String) -> Bool { 
    var bReturn:Bool=false; 
    var sSQL="ALTER TABLE " + sTable + " ADD COLUMN " + sFieldName + " INTEGER DEFAULT -1"; 
    var statement:COpaquePointer = nil 
    if sqlite3_prepare_v2(db, sSQL, -1, &statement, nil) != SQLITE_OK { 
     println("Failed to prepare statement") 
    }else{ 
     println("field " + sFieldName + " added to " + sTable); 
     bReturn=true; 
    } 
    return bReturn; 
} 

使用此代碼沒有添加字段,也沒有發生錯誤。 有什麼幫助嗎? (我想使用本地訪問sqlite和沒有額外的庫)

+0

您從控制檯獲得的輸出是什麼?你也沒有調用sqlite3_step()和sqlite3_finalize() –

回答

4

你只准備聲明,不執行它。您需要撥打sqlite3_step()sqlite3_finalize()方法來完成此過程。

func adddbfield(sFieldName:String, sTable:String) -> Bool 
{ 
    var bReturn:Bool = false; 
    var sSQL="ALTER TABLE " + sTable + " ADD COLUMN " + sFieldName + " INTEGER DEFAULT -1"; 
    var statement:COpaquePointer = nil 
    if sqlite3_prepare_v2(db, sSQL, -1, &statement, nil) != SQLITE_OK 
    { 
     println("Failed to prepare statement") 
    } 
    else 
    { 
     if sqlite3_step(statement) == SQLITE_DONE 
     { 
      println("field " + sFieldName + " added to " + sTable); 
     } 
     sqlite3_finalize(statement); 
     bReturn=true; 
    } 
    return bReturn; 
} 
+0

我只是忘了這一步,非常感謝! –

+0

@mcflysoft:很高興。快樂的編碼! –