I have spent days trying to figure out why slqlite3 using Swift either inserts a string with the last character missing or just empty all together. Research online has also proven itself to be a defeat; I just cannot understand that by following the standard procedure of:
- Open the connection to the database.
- Prepare the statement & bind the variables.
- Execute the statement & finalize it.
- Close the connection to the database.
Note: This is according to Apress' Beginning iPhone Development with Swift book.
Would anyone have an idea as to why the strings are not being inserted properly (or maybe the issue arises during selection?) ? Any help would be greatly appreciated.
The code used in my application is as follows:
Assume necessary variables have been created.
var database:COpaquePointer = nil
var result: Int32 = Int32()
func create () {
connect()
let createSQL = "CREATE TABLE IF NOT EXISTS artists (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(100) NOT NULL, last_updated INTEGER, created INTEGER);"
var errMsg:UnsafeMutablePointer<Int8> = nil
if sqlite3_exec(database, createSQL, nil, nil, &errMsg) != SQLITE_OK { println(errMsg) }
disconnect()
}
func connect () -> Bool { println("Connected to the db."); return sqlite3_open(path, &database) == SQLITE_OK }
func create () { connect() let createSQL = "CREATE TABLE IF NOT EXISTS artists (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(100) NOT NULL, last_updated INTEGER, created INTEGER);" var errMsg:UnsafeMutablePointer = nil if sqlite3_exec(database, createSQL, nil, nil, &errMsg) != SQLITE_OK { println(errMsg) } disconnect() }
func addArtist (title: String) -> Int32 {
connect()
var newItemId: Int32 = 0
let query = "INSERT INTO artists (title, last_updated, created) VALUES (?, ?, ?);"
var statement:COpaquePointer = nil
if sqlite3_prepare_v2(database, query, -1, &statement, nil) == SQLITE_OK {
sqlite3_bind_text(statement, 1, title, -1, nil)
sqlite3_bind_int(statement, 2, 0)
sqlite3_bind_int(statement, 3, Int32(NSDate().timeIntervalSince1970))
}
if sqlite3_step(statement) == SQLITE_DONE { newItemId = Int32(sqlite3_last_insert_rowid(database)) }
sqlite3_finalize(statement)
disconnect()
return newItemId
}