Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Databases

Perry natively implements clients for MySQL, PostgreSQL, SQLite, MongoDB, and Redis.

MySQL

import mysql from "mysql2/promise"

async function mysqlExample(): Promise<void> {
    const connection = await mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "password",
        database: "mydb",
    })

    const [rows] = await connection.execute("SELECT * FROM users WHERE id = ?", [1])
    console.log(rows)

    await connection.end()
}

PostgreSQL

import { Client } from "pg"

async function postgresExample(): Promise<void> {
    const client = new Client({
        host: "localhost",
        port: 5432,
        user: "postgres",
        password: "password",
        database: "mydb",
    })

    await client.connect()
    const result = await client.query("SELECT * FROM users WHERE id = $1", [1])
    console.log(result.rows)
    await client.end()
}

SQLite

import Database from "better-sqlite3"

function sqliteExample(): void {
    const db = new Database("mydb.sqlite")

    db.exec(`
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT,
        email TEXT
      )
    `)

    const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)")
    insert.run("Perry", "perry@example.com")

    const users = db.prepare("SELECT * FROM users").all()
    console.log(users)
}

MongoDB

import { MongoClient } from "mongodb"

async function mongoExample(): Promise<void> {
    const client = new MongoClient("mongodb://localhost:27017")
    await client.connect()

    const db = client.db("mydb")
    const users = db.collection("users")

    await users.insertOne({ name: "Perry", email: "perry@example.com" })
    const user = await users.findOne({ name: "Perry" })
    console.log(user)

    await client.close()
}

Redis

import Redis from "ioredis"

async function redisExample(): Promise<void> {
    const redis = new Redis()

    await redis.set("key", "value")
    const value = await redis.get("key")
    console.log(value) // "value"

    await redis.del("key")
    await redis.quit()
}

Next Steps