绑定参数
🌐 Binding parameters
all()、get()、iterate() 和 run() 方法在执行之前,会把参数绑定到预处理语句的参数上。参数可以是匿名的,也可以是有名字的。
🌐 The all(), get(), iterate(), and run() methods bind their arguments to
the parameters of the prepared statement before executing it. Parameters are
either anonymous or named.
匿名参数在 SQL 中写作 ?,并按传给方法的参数顺序绑定。?NNN 形式会将 SQLite 参数索引 NNN 分配给一个占位符。尽量避免混用编号参数和命名参数,因为它们共享参数索引。
🌐 Anonymous parameters are written as ? in SQL and are bound in order from the
arguments passed to the method. The ?NNN form assigns SQLite parameter index
NNN to a placeholder. Avoid mixing numbered and named parameters because they
share parameter indexes.
db.prepare('SELECT ? AS a, ? AS b').get('x', 42);
// { a: 'x', b: 42 }
db.prepare('SELECT ?2 AS a, ?1 AS b').get('first', 'second');
// { a: 'second', b: 'first' } 命名参数在 SQL 中以前缀字符 $、: 或 @ 开头。它们从作为第一个参数传入的对象中绑定。在 SQL 中重复一个名字会将同一个值绑定到每个出现的位置。
🌐 Named parameters begin with one of the prefix characters $, :, or @ in
SQL. They are bound from an object passed as the first argument. Repeating a
name in the SQL binds the same value to every occurrence.
db.prepare('SELECT $a AS a, $b AS b').get({ $a: 1, $b: 2 });
// { a: 1, b: 2 }
db.prepare('SELECT :a AS a').get({ ':a': 1 });
// { a: 1 }
db.prepare('SELECT @a AS a').get({ '@a': 1 });
// { a: 1 }
db.prepare('SELECT $k AS a, $k AS b').get({ k: 7 });
// { a: 7, b: 7 } 最后一个例子省略了对象键的前缀字符。默认情况下允许使用裸名字;关于它们的注意事项,请参见 statement.setAllowBareNamedParameters()。
🌐 The last example omits the prefix character from the object key. Bare names are
allowed by default; see statement.setAllowBareNamedParameters() for their
caveats.
绑定一个不属于语句参数的键会抛出 ERR_INVALID_STATE 错误,除非忽略未知的命名参数。参见 statement.setAllowUnknownNamedParameters()。
🌐 Binding a key that does not name a parameter of the statement throws an
ERR_INVALID_STATE error unless unknown named parameters are ignored. See
statement.setAllowUnknownNamedParameters().
请参见 JavaScript 和 SQLite 之间的类型转换 获取可以绑定的值。绑定任何其他值都会抛出 ERR_INVALID_ARG_TYPE 错误。
🌐 See Type conversion between JavaScript and SQLite for the values that can be
bound. Binding any other value throws an ERR_INVALID_ARG_TYPE error.