Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add column in a sqlite table in SWIFT

I try to add a column in a table with swift.

my code :

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

With this Code no field is added and no error occurs. Any help ? (I would like to use the native access to sqlite and no additional library)

like image 306
mcfly soft Avatar asked Jun 18 '15 08:06

mcfly soft


People also ask

How do I add two columns in SQLite?

How do I add multiple columns in SQLite? SQLite does not support adding multiple columns to a table using a single statement. To add multiple columns to a table, you must execute multiple ALTER TABLE ADD COLUMN statements.

How do I edit a table in SQLite?

Summary. Use the ALTER TABLE statement to modify the structure of an existing table. Use ALTER TABLE table_name RENAME TO new_name statement to rename a table. Use ALTER TABLE table_name ADD COLUMN column_definition statement to add a column to a table.

How do you populate a table in SQLite?

To insert data into a table, you use the INSERT statement. SQLite provides various forms of the INSERT statements that allow you to insert a single row, multiple rows, and default values into a table. In addition, you can insert a row into a table using data provided by a SELECT statement.


1 Answers

You are only preparing the statement, not executing it. You need to call sqlite3_step() and sqlite3_finalize() methods for completing 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;
}
like image 193
Midhun MP Avatar answered Nov 15 '22 03:11

Midhun MP