# How to do parameterized CRUD in SQLite

> Insert, read, update, and delete with positional parameters and a cursor, without concatenating SQL.

Source: https://crossfly.dev/docs/cookbook/data/crud — CrossFly documentation. Full docs as one file: https://crossfly.dev/llms-full.txt

# How to do parameterized CRUD in SQLite

**Purpose.** Execute INSERT/UPDATE/DELETE and SELECT with **positional parameters** (`?`), avoiding string concatenation (which causes SQL injection and quoting errors). Pay attention to CrossFly's two index conventions.

> ⚠️ **Indexes.** When **binding** parameters, the indexes are **1-based** (`?` no. 1, 2, ...). When **reading** columns from the cursor, the indexes are **0-based** (`getString(0)` = first column). This is intentional and mirrors SQLite's native API.

## APIs used
- `SqliteDb.execute(String sql, Object... params)` — prepares, does `bindAll(params)` (**1-based** bind), executes a single INSERT/UPDATE/DELETE, and returns the **number of affected rows** (`int`). Types are inferred: `Integer/Long/Short/Byte`→integer, `Float/Double`→real, `Boolean`→0/1, `byte[]`→BLOB, `null`→NULL, otherwise `toString()`→TEXT.
- `SqliteDb.query(String sql, Object... params)` — returns an **open** `SqliteCursor` (1-based bind). The caller **must close it** (use `try-with-resources`).
- `SqliteCursor.next()` — advances to the next row; returns `true` if there is a row.
- `SqliteCursor.getInt(col)/getLong/getDouble/getString/getBlob/isNull(col)` — typed getters, **0-based** column.
- `SqliteDb.queryLong(sql, defaultValue, params)` — shortcut: 1st column of the 1st row as a `long`, or `defaultValue` if there are no rows.
- `SqliteDb.queryString(sql, params)` — shortcut: 1st column of the 1st row as a `String`, or `null` if there are no rows.
- `SqliteDb.lastInsertRowid()` — rowid of the last INSERT (`long`). `SqliteDb.changes()` — rows changed by the last statement.

## Full example (copy, paste and run)

```java
package com.exemplo;

import dev.crossfly.ui.*;                     // Window
import dev.crossfly.ui.layout.*;             // VerticalLayout
import dev.crossfly.sqlite.*;                // SqliteDb, SqliteCursor

/** Runnable main screen. Point the launcher (classname) and run: gradlew :lwjgl3:run */
public class MainWindow extends Window
{
   @Override
   public void onShow() throws Exception
   {
      super.onShow();
      setLayout(new VerticalLayout());

      try (SqliteDb db = SqliteDb.open("app.db"))
      {
         db.exec("CREATE TABLE IF NOT EXISTS person(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)");

         // CREATE — positional parameters (? no. 1 = name, ? no. 2 = age)
         int inserted = db.execute("INSERT INTO person(name, age) VALUES(?, ?)", "Alice", 30);
         long id = db.lastInsertRowid();            // generated rowid
         System.out.println(inserted + " linha(s), id=" + id);

         // READ — cursor: columns 0-based
         try (SqliteCursor c = db.query("SELECT name, age FROM person WHERE age > ?", 18))
         {
            while (c.next())
               System.out.println(c.getString(0) + " = " + c.getInt(1));   // col 0 = name, col 1 = age
         }

         // scalar READ — shortcuts
         long total = db.queryLong("SELECT count(*) FROM person", 0);
         String nome = db.queryString("SELECT name FROM person WHERE id = ?", id);

         // UPDATE — returns the number of affected rows
         int updated = db.execute("UPDATE person SET age = ? WHERE id = ?", 31, id);

         // DELETE
         int deleted = db.execute("DELETE FROM person WHERE id = ?", id);
      }
   }
}
```

> The snippet below shows **only the core**. To run it, place it inside the `MainWindow` skeleton above.

## Minimal snippet
```java
// verified at source: execute (bind 1-based), query + cursor (getters 0-based), queryLong/queryString
import dev.crossfly.sqlite.*;

try (SqliteDb db = SqliteDb.open("app.db"))
{
   db.exec("CREATE TABLE IF NOT EXISTS person(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)");

   // CREATE — positional parameters (? no. 1 = name, ? no. 2 = age)
   int inserted = db.execute("INSERT INTO person(name, age) VALUES(?, ?)", "Alice", 30);
   long id = db.lastInsertRowid();            // generated rowid
   System.out.println(inserted + " linha(s), id=" + id);

   // READ — cursor: columns 0-based
   try (SqliteCursor c = db.query("SELECT name, age FROM person WHERE age > ?", 18))
   {
      while (c.next())
         System.out.println(c.getString(0) + " = " + c.getInt(1));   // col 0 = name, col 1 = age
   }

   // scalar READ — shortcuts
   long total = db.queryLong("SELECT count(*) FROM person", 0);
   String nome = db.queryString("SELECT name FROM person WHERE id = ?", id);

   // UPDATE — returns the number of affected rows
   int updated = db.execute("UPDATE person SET age = ? WHERE id = ?", 31, id);

   // DELETE
   int deleted = db.execute("DELETE FROM person WHERE id = ?", id);
}
```

## Dig deeper
- [SQLite storage guide](/docs/data-and-services/storage-sqlite) · Development guide
- Sibling recipes: [Open/create a database](/docs/cookbook/data/abrir-banco) · [Transaction and bulk writing](/docs/cookbook/data/transacao-e-bulk) · [Use outside the paint thread](/docs/cookbook/data/banco-fora-da-paint-thread)
