Better-sqlite3 绑定参数

来自泡泡学习笔记
跳到导航 跳到搜索

本节指的是文档中任何指定可选参数[...bindParameters]的地方。


有许多方法可以将参数绑定到预处理语句。最简单的方法是使用匿名参数:

const stmt = db.prepare('INSERT INTO people VALUES (?, ?, ?)');

// 以下等价。
stmt.run('John', 'Smith', 45);
stmt.run(['John', 'Smith', 45]);
stmt.run(['John'], ['Smith', 45]);


你也可以使用命名参数。SQLite3提供了3种不同的命名参数语法@foo:foo$foo),所有这些都由better-sqlite3支持。

// 以下等价。
const stmt = db.prepare('INSERT INTO people VALUES (@firstName, @lastName, @age)');
const stmt = db.prepare('INSERT INTO people VALUES (:firstName, :lastName, :age)');
const stmt = db.prepare('INSERT INTO people VALUES ($firstName, $lastName, $age)');
const stmt = db.prepare('INSERT INTO people VALUES (@firstName, :lastName, $age)');

stmt.run({
  firstName: 'John',
  lastName: 'Smith',
  age: 45
});


下面是一个将匿名参数与命名参数混合的例子。

const stmt = db.prepare('INSERT INTO people VALUES (@name, @name, ?)');
stmt.run(45, { name: 'Henry' });


这里是better-sqlite3如何将SQLite3和JavaScript之间的值进行转换的示例:

SQLite3 JavaScript
NULL null
REAL number
INTEGER number BigInt
TEXT string
BLOB Buffer