Skip to content

Instantly share code, notes, and snippets.

@odemolliens
Forked from zgchurch/BridgingHeader.h
Created September 21, 2016 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odemolliens/a4c0c8fb6e5931229fdd0d3c9c92adcc to your computer and use it in GitHub Desktop.
Save odemolliens/a4c0c8fb6e5931229fdd0d3c9c92adcc to your computer and use it in GitHub Desktop.
Using SQLite3 from Swift
// 1. Create this file in your Xcode project
// 2. Go to "Build Settings" and find "Objective-C Bridging Header." Use the search bar to find it quickly.
// 3. Double-click and type "BridgingHeader.c"
// If you get "Could not import Objective-C Header," try "my-project-name/BridgingHeader.h"
// 4. Go to "Build Phases," "Link Binary With Libraries," and add libsqlite3.0.dylib
#include <sqlite3.h>
import Foundation
var db: COpaquePointer = nil;
if sqlite3_open("/Users/zchurch/Code/testapp/db/development.sqlite3", &db) != SQLITE_OK {
println("Failed to open file")
exit(1)
}
var sql = "SELECT * FROM schema_migrations"
var statement:COpaquePointer = nil
var tail: CString = ""
if sqlite3_prepare_v2(db, sql.bridgeToObjectiveC().UTF8String, sql.lengthOfBytesUsingEncoding(NSUTF8StringEncoding).bridgeToObjectiveC().intValue, &statement, &tail) != SQLITE_OK {
println("Failed to prepare statement")
exit(1)
}
func print_row(s: COpaquePointer) {
for i in 0..sqlite3_column_count(s) {
switch sqlite3_column_type(s, i) {
case SQLITE_INTEGER:
var r = sqlite3_column_int(s, i)
case SQLITE_TEXT:
var r = CString(sqlite3_column_text(s, i))
println("String: \(r)")
default:
println("Other column type")
}
}
}
var complete = false
while complete == false {
switch sqlite3_step(statement){
case SQLITE_DONE:
println("Done executing statement")
case SQLITE_ROW:
println("Row")
print_row(statement)
default:
println("Other")
complete = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment