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 query
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 creation
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 query
import { sqlite } from "https://esm.town/v/std/sqlite";
console.log(await sqlite.execute(`select key, value from kv`));

Insert data

Data insertion
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 deletion
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 queries
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 },
},
]);