Bart Simons

Bart Simons

Thoughts, stories and ideas.

Bart Simons



.net .net 5 .net core Apache C# CentOS LAMP NET Framework Pretty URLs Windows Server WireGuard access log add analysis android api at the same time authentication authorization automate automation azure azurerm backup bash basics batch bootstrap build capture cheat sheet chromium chroot class cli click to close code coverage code snippet command line commands compile compiling compression containers control controller controlling convert cpu usage create credentials csv csvparser curl data dd deployment desktop detect devices disable diskpart dism distributed diy docker dom changes dotnet core drivers ease of access encryption example export file transfer files fix folders framework generalize getting started ghost gui guide gunicorn gzip html html tables icewarp igd imagex import inotify install installation interactive ios iphone itunes java javascript jquery json kiosk kotlin linux live load data loading screen lock screen loopback audio lxc lxd lxml macos manage manually message messages minio mirrored mod_rewrite monitor monitoring mstest mutationobserver mysql net 5 nexmo nginx no oobe node node.js nodejs not installing notification notifications object storage on desktop one command openssl owncloud parallels parallels tools parse perfect philips hue play port forwarding powershell processing ps-spotify python quick raspberry pi record rip ripping rsync rtmp save save data sbapplication scraping script scripting scriptingbridge scripts security send server service sharedpreferences sms songs sonos spotify spotify api spotlight ssh stack streaming streamlink studio sudo swarm swift sync sysprep system audio systemd tables terminal testing tracking tutorial twilio ubiquiti ubuntu ubuntu 18.04 ui code unifi unlock unsplash source upnp uptime usb tethering wallpapers wasapi website websites webview windows windows 10 without itunes without oobe workaround xaml

Using MySQL in Swift with Perfect

So I recently got a chance to play around with Perfect - a "web app framework" for Swift that provides you with multiple building blocks to get your project going. One of the really neat things about this framework is that it contains anything you need to get stuff connected. I came across their MySQL library that can be used in projects with or without the other Perfect dependencies involved. You can't get any more modular than this!

My development environment

I tend to always use Linux for my projects, and this little project is no exception. My dev box is equipped with the following stuff:

You also need to install the libmysqlclient-dev package through apt-get in order to use and build the Swift MySQL package.

Creating a new project

Create a new directory for this project on your server. I called mine mysql-app. Change your current directory to that directory and run swift package init --type executable to generate a blank Swift project. If you have a Mac and plan to use Xcode for your project: you can initialize an Xcode project file with swift package generate-xcodeproj

Adding Perfect-MySQL to the project

Edit your Package.swift file and include Perfect-MySQL as a dependency, like this:

import PackageDescription

let package = Package(
    name: "mysql-app",
    dependencies: [
    	.Package(url: "", majorVersion: 2)

Now it's time to write some code!

The database structure

The code

Just put the following code inside Sources/main.swift:

import MySQL

let sqlHost     = ""
let sqlUser     = "app_authentication"
let sqlPassword = "testing01"
let sqlDB       = "app_authentication"

func fetchData()
	let mysql   = MySQL()
	guard mysql.connect(host: sqlHost, user: sqlUser, password: sqlPassword, db: sqlDB) else

	defer {

	let theStatement = MySQLStmt(mysql)
	_ = theStatement.prepare(statement: "SELECT * FROM users")
	_ = theStatement.execute()

	let theResults = theStatement.results()


	_ = theResults.forEachRow {
		e in

		for i in 0..<e.count {
			let theFieldName = theStatement.fieldInfo(index: i)!.name
			print("\(theFieldName): \(e[i]!)")



Build and run

Just run swift build to build your project and run .build/debug/mysql-app to run your application. It should return this as the output in your terminal:

Extra information

I made this small tutorial after I had to fiddle around with this library for one whole day. The documentation suggests to use mysql.query to run queries, but there's too little information available about running prepared statements. Not only in the documentation of Perfect, but also on the whole web. Then - a couple hours later - I discovered the MySQLStmt class, after digging into the Swift Tests available on their Github repo.

Another reason to only use the MySQLStmt class is because the class contains a function called fieldInfo which returns the name of a column by ID. mysql.query simply doesn't have that...

Oh well, at least I got some of my code fixed today. Enjoy programming in Swift!

Bart Simons

Bart Simons

View Comments