Joseph Jude

Export sqlite data to text files using Swift

2016.04.28 / code / swift /

Export sqlite data to text files using Swift

I had my blog post details in a sqlite. I wanted them converted into text files, so that I can store them in a git repository.

Though I could've written the script in python, I wanted to try swift. Surprisingly, it was easy to do in swift. I used two toolkits—SQLite and FileKit, which made this easy.

I used Carthage as a package manager. If you want a good tutorial on Carthage, checkout the tutorial at Ray Wenderlich.

Once you install carthage, create a cartfile for the frameworks:

github "stephencelis/SQLite.swift" ~> 0.10.1
github "nvzqz/FileKit"

Now, you have to download these frameworks and build them locally. carthage update --no-use-binaries will just do that.

Here is the code to connect to sqlite and export the content of a table into a structure text file:

#!/usr/bin/swift -F Carthage/Build/Mac/

// Tell Swift where to find sqlite & filekit framework.

import SQLite
import FileKit

let db = try Connection("posts.db")

let fileDirectory = Path.Current + "out"
var fileName = ""

for row in try db.prepare("SELECT * FROM entry") {
    // construct fileName; convert path & row value to string
    fileName = String(fileDirectory) + "/" + String(row[6]!) + ".md"

    // convert string to Path
    let postFile = TextFile(path: Path(fileName))

    try "Site: " + String(row[1]!) |> postFile
    try "Title: " + String(row[9]!) |>> postFile
    try "Subtitle: " + String(row[7]!) |>> postFile
    try "Date: " + String(row[5]!) |>> postFile
    try "Slug: " + String(row[6]!) |>> postFile
    try "Tags: " + String(row[8]!) |>> postFile
    try "Type: " + String(row[4]!) |>> postFile
    try "Excerpt: " + String(row[3]!) |>> postFile
    try "

Share this post on

Twitter | | |
Sign up for my weekly newsletter

I will send blog updates to this email. You can unsubscribe at any time using the link in those emails.