How to add column in sqlite table in SWIFT

I am trying to add a column to a table with speed.

my code is:

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

In this case, the "Code" field is not added and no errors occur. Any help? (I would like to use native access to sqlite and no additional library)

+5
source share
1 answer

You are only preparing an expression, not performing it. You need to call the sqlite3_step() and sqlite3_finalize() methods to complete the process.

 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; } 
+4
source

All Articles