Last active
March 19, 2019 13:35
-
-
Save dkw5877/70abbc1c8d55eac9759ccefdf099e8ae to your computer and use it in GitHub Desktop.
Example of CREATE statement using FMDB for SQLite
This file contains hidden or 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
| /* | |
| * @description: creates a table with the specified list of columns and value types | |
| * @note statement example e.g."CREATE TABLE IF NOT EXISTS table_name (Title Text, Author Text, PublicationDate Date)" | |
| * @param table name of the table to create | |
| * @param columns list of TableColumn values to create the columns | |
| * @param completion closure to be called when create is complete | |
| */ | |
| static func create(table:String, columns:[TableColumn], completion:Completion) { | |
| var sqlStatement = "CREATE TABLE IF NOT EXISTS \(table) (ID Integer Primary key AutoIncrement," | |
| for (index, column) in columns.enumerated() { | |
| sqlStatement += " \(column.name) \(column.type)" | |
| sqlStatement += (index == columns.count - 1) ? ");" :"," | |
| } | |
| FMDBDatabase.update(sqlStatement: sqlStatement, completion: completion) | |
| } | |
| /* | |
| * @description: All transactions in FMDB are an UPDATE if they are not a QUERY, this | |
| * helper method is called by the CREATE, INSERT, and DELETE functions | |
| * @param sqlStatement the complete SQL statement to execute | |
| * @param values list of TableColumn or WhereConditions values to use in update | |
| * @param completion closure to be called when update is complete | |
| */ | |
| private static func update(sqlStatement:String, values:[Any]? = nil, completion:Completion) { | |
| sharedQueue.inDeferredTransaction { (db, rollback) in | |
| do { | |
| if !sharedDatabase.isOpen { | |
| sharedDatabase.open() | |
| } | |
| try sharedDatabase.executeUpdate(sqlStatement, values: values) | |
| completion(true, nil) | |
| sharedDatabase.close() | |
| } catch { | |
| print("failed: \(error.localizedDescription)") | |
| completion(false, error) | |
| sharedDatabase.close() | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment