Working with Databases in Swift: PostgreSQL and MongoDB for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Swift and Databases?

\n

Swift is not just a language for creating mobile applications. Thanks to frameworks like Vapor and SwiftNIO, developers can build full-fledged server applications that interact with relational and document-oriented databases. In this article, we will cover how to connect to PostgreSQL and MongoDB from Swift, and show simple code examples for beginners.

\n

The article is aimed at those who are already familiar with the basics of Swift but are just starting to learn how to work with databases. We will look at two popular approaches: classic SQL (PostgreSQL) and flexible NoSQL (MongoDB).

\n\n

1. PostgreSQL in Swift: Structured Data

\n

PostgreSQL is a powerful open-source relational database. To work with it in Swift, we will use the PostgresKit package, which is part of the Vapor ecosystem.

\n\n

1.1 Installation and Setup

\n

Add the dependency to the Package.swift file:

\n
// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n    name: "MyApp",\n    dependencies: [\n        .package(url: "https://github.com/vapor/postgres-kit.git", from: "2.0.0")\n    ],\n    targets: [\n        .executableTarget(\n            name: "MyApp",\n            dependencies: [\n                .product(name: "PostgresKit", package: "postgres-kit")\n            ]\n        )\n    ]\n)
\n\n

1.2 Connecting to the Database

\n

Create a configuration instance and connect to the PostgreSQL server:

\n
import PostgresKit\n\nlet eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)\ndefer { try! eventLoopGroup.syncShutdown() }\n\nlet configuration = PostgresConfiguration(\n    hostname: "localhost",\n    port: 5432,\n    username: "swift_user",\n    password: "secret",\n    database: "swift_db"\n)\n\nlet pool = EventLoopGroupConnectionPool(\n    source: PostgresConnectionSource(configuration: configuration),\n    on: eventLoopGroup\n)\ndefer { try! pool.syncShutdown() }\n\nlet connection = try pool.requestConnection().wait()\nprint("Connection to PostgreSQL established!")
\n\n

1.3 Executing SQL Queries

\n

Now let's execute a simple query to create a table and insert data:

\n
// Create users table\ntry connection.query("""\n    CREATE TABLE IF NOT EXISTS users (\n        id SERIAL PRIMARY KEY,\n        name TEXT NOT NULL,\n        email TEXT UNIQUE NOT NULL\n    )\n""").wait()\n\n// Insert data\ntry connection.query("""\n    INSERT INTO users (name, email) \n    VALUES ('Alexey', 'alex@example.com')\n""").wait()\n\n// Read data\nlet rows = try connection.query("SELECT * FROM users").wait()\nfor row in rows {\n    let id = try row.decode(Int.self, column: "id")\n    let name = try row.decode(String.self, column: "name")\n    let email = try row.decode(String.self, column: "email")\n    print("User: \\(name) (\\(email)), ID: \\(id)")\n}
\n\n

2. MongoDB in Swift: Flexible Documents

\n

MongoDB is a NoSQL database that stores data in JSON-like documents. There are several drivers for Swift, but we will use the official MongoDB Swift Driver.

\n\n

2.1 Installing the Driver

\n

Add the package to Package.swift:

\n
dependencies: [\n    .package(url: "https://github.com/mongodb/mongo-swift-driver.git", from: "1.0.0")\n],\ntargets: [\n    .executableTarget(\n        name: "MyApp",\n        dependencies: [\n            .product(name: "MongoSwift", package: "mongo-swift-driver")\n        ]\n    )\n]
\n\n

2.2 Connecting to MongoDB

\n

Create a client and select a database:

\n
import MongoSwift\n\nlet client = try MongoClient("mongodb://localhost:27017")\ndefer { try? client.syncClose() }\n\nlet database = client.db("swift_m                

Blogs

Book Recommendations