Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 11
Basic usage
Each library conforming to SQL implements its own method of connecting. In PostgreSQL it looks like this:
letconnection=Connection(host:"localhost", databaseName:"my_database")Each driver should have a Connection constructor you can use to provide connection details.
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()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)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.
forrowintry connection.execute("SELECT * FROM artists"){letname:String=try row.value("name")letdata=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.
CREATETABLEIF NOT EXISTS artists(
id SERIALPRIMARY KEY,
genre VARCHAR(50), # Note how this field is nullable
name VARCHAR(255) NOT NULL
)// Will throw an error if genre is NULL
letgenre:String=try row.value("genre")
// Works as expected
letgenre:String?=try row.value("genre")
// Will throw an error. Field is missing
letiDontExist:String?=try row.value("something")