Skip to content

Usage

The Val Town SQLite val has two methods: execute and batch . Below are examples of how to use them in Val Town.

Simple query

Simple queryRun in Val Town ↗
import { sqlite } from "https://esm.town/v/std/sqlite";
const data = await sqlite.execute("SELECT datetime();");
console.log(data.rows[0]);

Create a table

Table creationRun in Val Town ↗
import { sqlite } from "https://esm.town/v/std/sqlite";
await sqlite.execute(`create table if not exists kv(
key text unique,
value text
)`);

Get data

Data queryRun in Val Town ↗
import { sqlite } from "https://esm.town/v/std/sqlite";
console.log(await sqlite.execute(`select key, value from kv`));

Insert data

Data insertionRun in Val Town ↗
import { sqlite } from "https://esm.town/v/std/sqlite";
await sqlite.execute({
sql: `insert into kv(key, value) values (:key, :value)`,
args: { key: "specialkey", value: "specialvalue" },
});

Delete data

Data deletionRun in Val Town ↗
import { sqlite } from "https://esm.town/v/std/sqlite";
await sqlite.execute({
sql: `delete from kv where key = :key`,
args: { key: "specialkey" },
});

Batch queries

Batching queriesRun in Val Town ↗
import { sqlite } from "https://esm.town/v/std/sqlite";
const charge = 10;
export const batchSqlite = await sqlite.batch([
`create table if not exists accounts(person_id text unique, balance integer)`,
{
sql: `update accounts set balance = balance - :charge where person_id = 'Bob'`,
args: { charge },
},
{
sql: `update accounts set balance = balance + :charge where person_id = 'Alice'`,
args: { charge },
},
]);