Skip to content

Basic usage

David Ask edited this page Apr 7, 2016 · 7 revisions

Connecting to a database

Each library conforming to SQL implements its own method of connecting. In PostgreSQL it looks like this:

let connection = Connection(host: "localhost", databaseName: "my_database")

Each driver should have a Connection constructor you can use to provide connection details.

Opening and closing a connection

Opening a connection is easy.

try connection.open()

Closing is usually not needed, as the connection will close automatically when there are no references to the connection class. You can, however, do it manually.

connection.close()

Executing raw queries

You can run queries simply by passing a String to the connections execute method.

try connection.execute("SELECT * FROM artists")

You can pass parameters to protect your queries from SQL injection.

try connection.execute("SELECT * FROM artists where id = %@", parameters: 1)

Getting values from results

When executing queries, using the execute method, you will receive a Result object for your specific driver. The Result object is a CollectionType that may contain generator elements of Row, depending on your query.

for row in try connection.execute("SELECT * FROM artists") {
    let name: String = try row.value("name")
    let data = try row.data("name")
}

When accessing values from a Row, you can either ask for a value or Data. When asking for a value, you need to explicitly declare the type of the value you are expecting, including if it's optional or not. This helps with the data integrity of your application, as Row will throw an error if it finds a null value where you've declared a non-optional type. Similarly, Row will throw an error if the field is not present in the result.

For example, this table has a non-null field called name, and a nullable field called genre.

CREATE TABLE IF NOT EXISTS artists(
id SERIAL PRIMARY KEY,
genre VARCHAR(50), # Note how this field is nullable
name VARCHAR(255) NOT NULL
)
// Will throw an error if genre is NULL
let genre: String = try row.value("genre")

// Works as expected
let genre: String? = try row.value("genre")

// Will throw an error. Field is missing
let iDontExist: String? = try row.value("something")