A stand-alone Swift wrapper around the SQLite 3 client library.

Overview

Perfect - SQLite Connector

Get Involed with Perfect!

Star Perfect On Github Stack Overflow Follow Perfect on Twitter Join the Perfect Slack

Swift 4.0 Platforms OS X | Linux License Apache PerfectlySoft Twitter Slack Status

This project provides a Swift wrapper around the SQLite 3 library.

This package builds with Swift Package Manager and is part of the Perfect project. It was written to be stand-alone and so does not require PerfectLib or any other components.

Ensure you have installed and activated the latest Swift 4.0 tool chain.

To learn more, you can read the full documentation guide here or jump to the example here

Linux Build Notes

Ensure that you have installed sqlite3.

sudo apt-get install sqlite3

Building

Add this project as a dependency in your Package.swift file.

.Package(url: "https://github.com/PerfectlySoft/Perfect-SQLite.git", majorVersion: 3)

Edge Case

If you encounter error like such sqlite3.h file not found during $ swift build , one solution is to install the sqlite3-dev i.e. $ sudo apt-get install libsqlite3-dev

Usage Example

Let’s assume you’d like to host a blog in Swift. First we need tables. Assuming you’ve created an SQLite file ./db/database, we simply need to connect and add the tables.

let dbPath = "./db/database"

do {
	let sqlite = try SQLite(dbPath)
	defer {  
		sqlite.close()
	}

	try sqlite.execute(statement: "CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY NOT NULL, post_title TEXT NOT NULL, post_content TEXT NOT NULL, featured_image_uri TEXT NOT NULL)")
} catch {
	print("Failure creating database tables") //Handle Errors
}

Next, we would need to add some content.

let dbPath = "./db/database"
let postTitle = "Test Title"
let postContent = "Lorem ipsum dolor sit amet…"

do {
   let sqlite = try SQLite(dbPath)
   defer {
     sqlite.close()
   }

   try sqlite.execute(statement: "INSERT INTO posts (post_title, post_content) VALUES (:1,:2)") {
     (stmt:SQLiteStmt) -> () in

     try stmt.bind(position: 1, postTitle)
     try stmt.bind(position: 2, postContent)
   }
 } catch {
		//Handle Errors
 }

Finally, we retrieve posts and post titles from an SQLite database full of blog content. Each id, post, and title is appended to a dictionary for use elsewhere.

let dbPath = "./db/database"
var contentDict = [String: Any]()

do {
	let sqlite = try SQLite(dbPath)
		defer {
			sqlite.close() // This makes sure we close our connection.
		}
	
	let demoStatement = "SELECT post_title, post_content FROM posts ORDER BY id DESC LIMIT :1"
	
	try sqlite.forEachRow(statement: demoStatement, doBindings: {
		
		(statement: SQLiteStmt) -> () in
		
		let bindValue = 5
		try statement.bind(position: 1, bindValue)
		
	}) {(statement: SQLiteStmt, i:Int) -> () in

        self.contentDict.append([
                "id": statement.columnText(position: 0),
                "second_field": statement.columnText(position: 1),
                "third_field": statement.columnText(position: 2)
            ])
  }
	
} catch {
	//Handle Errors
}

Further Information

For more information on the Perfect project, please visit perfect.org.

You might also like...
Implement Student Admission System using SQlite
Implement Student Admission System using SQlite

StudentAdmissionSQLiteApp Implement Student Admission System using SQlite. #Func

BucketServer - Small API with SQLite database that saves notes for an iOS appliction called Bucket list

BucketList Server-Side Small API with SQLite database that saves notes for an iO

macOS Sqlite tableView 샘플 - objective c

목적 Objective C언어를 이용하여 macOS를 개발해본다. Sqlite를 이용하여 데이터를 저장하고, 불러와본다. FMDB를 이용한다. 데이터를 NSTableView를 이용하여 불러와본다. 추가적으로 NSOutlineView 구현해본다. 추가적으로 KVOCont

MagicData - A replacement of SQlite, CoreData or Realm.

MagicData A replacement of SQlite, CoreData or Realm. It is very easy to use and is a light version. Guides MagicData We use MagicData manage all the

iForage helps foragers to track and manage foraging spots around them using CloudKit
iForage helps foragers to track and manage foraging spots around them using CloudKit

iForage CloudKit Preface To expand on what I've created here: https://github.com/LynchConnor/iForage, I initially developed the app using Firebase. Th

A PostgreSQL client library for Swift. Does not require libpq.

PostgresClientKit PostgresClientKit provides a friendly Swift API for operating against a PostgreSQL database. Features Doesn't require libpq. Postgre

CoreData/Realm sweet wrapper written in Swift
CoreData/Realm sweet wrapper written in Swift

What is SugarRecord? SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way. Than

A Swift wrapper for system shell over posix_spawn with search path and env support.

AuxiliaryExecute A Swift wrapper for system shell over posix_spawn with search path and env support. Usage import AuxiliaryExecute AuxiliaryExecute.l

An Objective-C wrapper for RocksDB - A Persistent Key-Value Store for Flash and RAM Storage.

ObjectiveRocks ObjectiveRocks is an Objective-C wrapper of Facebook's RocksDB - A Persistent Key-Value Store for Flash and RAM Storage. Current RocksD

Comments
  • Extended the SQLiteStmt class with isNull(), isText(), isBlob(), etc

    Extended the SQLiteStmt class with isNull(), isText(), isBlob(), etc

    Question: Should the name of the isFloat() function be changed to isDouble() ?

    The constant is named SQLITE_FLOAT, so it may make sense to keep the isFloat() name.

    It's a great framework you have. I like it. It works very well.

    opened by neoneye 3
  • when i build target,has no member in xcode 10

    when i build target,has no member in xcode 10

    123:RhinoAppActiveServer xiang$ swift build /Users/xiang/Desktop/server/RhinoAppActiveServer: error: manifest parse error(s): /Users/xiang/Desktop/server/RhinoAppActiveServer/Package.swift:12:10: error: type 'Package.Dependency' has no member 'Package' .Package(url: "https://github.com/PerfectlySoft/Perfect-SQLite.git", from: "3.0.0"), ^~~~~~~ 123:RhinoAppActiveServer xiang$

    opened by XMSECODE 1
  • Blob is [Int8], but NSData constructor expects [UInt8]

    Blob is [Int8], but NSData constructor expects [UInt8]

    I think it will be more convenient if Blob will use [UInt8] too. In many situations data fetched from Blob columns will be passed to functions expecting (NS)Data.

    opened by zmeyc 0
  • Making closure parameters non-escaping where possible (forEachRow etc)

    Making closure parameters non-escaping where possible (forEachRow etc)

    Please consider marking closures in methods such as forEachRow non escaping (@noescape attribute). They aren't capturing the closure anyway, but if this attribute is absent, closure requires prefixing member references with explicit 'self.'

                try DB.connection.forEachRow(statement: "SELECT * FROM topics_files WHERE user_id = ?", doBindings: { statement in
                    try statement.bind(position: 0, self.userId!) // <---- self.
                }) { statement, row in
                    self.topicsData = statement.columnBlob(position: 0) // <---- self.
                }
    
        public func forEachRow(statement: String, doBindings: @noescape (SQLiteStmt) throws -> (), handleRow: @noescape (SQLiteStmt, Int) -> ()) throws {}
    ...
        func forEachRowBody(stat: SQLiteStmt, handleRow: @noescape (SQLiteStmt, Int) -> ()) throws {}
    ...
    etc
    
    opened by zmeyc 1
Owner
PerfectlySoft Inc.
Server-side Swift
PerfectlySoft Inc.
A stand-alone Swift wrapper around the MySQL client library, enabling access to MySQL servers.

Perfect - MySQL Connector This project provides a Swift wrapper around the MySQL client library, enabling access to MySQL database servers. This packa

PerfectlySoft Inc. 118 Jan 1, 2023
A stand-alone Swift wrapper around the libpq client library, enabling access to PostgreSQL servers.

Perfect - PostgreSQL Connector This project provides a Swift wrapper around the libpq client library, enabling access to PostgreSQL servers. This pack

PerfectlySoft Inc. 51 Nov 19, 2022
A stand-alone Swift wrapper around the FileMaker XML Web publishing interface, enabling access to FileMaker servers.

Perfect - FileMaker Server Connector This project provides access to FileMaker Server databases using the XML Web publishing interface. This package b

PerfectlySoft Inc. 33 Jul 13, 2022
A Cocoa / Objective-C wrapper around SQLite

FMDB v2.7 This is an Objective-C wrapper around SQLite. The FMDB Mailing List: https://groups.google.com/group/fmdb Read the SQLite FAQ: https://www.s

August 13.7k Dec 28, 2022
A Swift wrapper for SQLite databases

Squeal, a Swift interface to SQLite Squeal provides access to SQLite databases in Swift. Its goal is to provide a simple and straight-forward base API

Christian Niles 297 Aug 6, 2022
SQLite.swift - A type-safe, Swift-language layer over SQLite3.

SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

Stephen Celis 8.7k Jan 3, 2023
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

Yap Studios 3.3k Dec 29, 2022
Swift APIs for SQLite: Type-safe down to the schema. Very, very, fast. Dependency free.

Lighter Lighter is a set of technologies applying code generation to access SQLite3 databases from Swift, e.g. in iOS applications or on the server. L

Lighter.swift 330 Dec 26, 2022
A toolkit for SQLite databases, with a focus on application development

A toolkit for SQLite databases, with a focus on application development

Gwendal Roué 5.6k Jan 8, 2023
Realm is a mobile database: a replacement for Core Data & SQLite

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & wa

Realm 15.7k Jan 1, 2023