Created
August 31, 2019 18:17
-
-
Save robertmryan/b6e7e32de1f1c3d79d5c151eaa32643e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func retrieveArticles(searchText: String) { | |
precondition(db != nil, "Database not open") | |
articles.removeAll() | |
let query = "SELECT * FROM articles WHERE title = ? " | |
var statement: OpaquePointer? | |
guard sqlite3_prepare(db, query, -1, &statement, nil) == SQLITE_OK else { | |
let errmsg = String(cString: sqlite3_errmsg(db)!) | |
print("error preparing Select: \(errmsg)") | |
return | |
} | |
defer { sqlite3_finalize(statement) } | |
guard sqlite3_bind_text(statement, 1, searchText, -1, nil) == SQLITE_OK else { | |
let errmsg = String(cString: sqlite3_errmsg(db)!) | |
print("failure binding title: \(errmsg)") | |
return | |
} | |
while sqlite3_step(statement) == SQLITE_ROW { | |
let id = sqlite3_column_int(statement, 0) | |
let author = sqlite3_column_text(statement, 1) | |
let title = sqlite3_column_int(statement, 2) // is title really an integer? | |
if let author = author { | |
articles.append(Article(id: Int(id), author: String(cString: author), title: "\(title)")) | |
} else { | |
print("Author is required") | |
} | |
} | |
print(articles.count) | |
print(articles) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A few observations:
defer
thesqlite3_finalize
so that it's called, regardless of how you exit this routine.guard
, in which the compiler verifies that you have returned.String(describing:)
is not what you want.*
is SQLSELECT
statements because one's code should not be dependent upon the sequence of columns in the table. It's probably prudent to explicitly list the column names.statement
instead ofstmt3
; theArticleList
should also start with lowercase letter, and I’d personally just call itarticles
; etc.).