2015-06-18 17 views
5

Provo ad aggiungere una colonna in una tabella con swift.come aggiungere una colonna in una tabella sqlite in SWIFT

il mio codice:

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; 
} 

Con questo codice non viene aggiunto alcun campo e non si verifica alcun errore. Qualche aiuto? (Vorrei utilizzare l'accesso nativo a sqlite e nessuna libreria aggiuntiva)

+0

Qual è l'output che si ottiene dalla console? Inoltre non hai chiamato sqlite3_step() e sqlite3_finalize() –

risposta

4

Stai solo preparando la dichiarazione, non eseguendola. È necessario chiamare i metodi sqlite3_step() e sqlite3_finalize() per completare il processo.

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

Ho semplicemente dimenticato il passaggio, grazie mille! –

+0

@mcflysoft: Con piacere. Buona programmazione! –