简体   繁体   English

如何在节点js上使用npm sqlite库的Prepared statements

[英]How to use Prepared statements with npm sqlite library on node js

I am using this library for connecting my node js application to an sqlite database.我正在使用这个库将我的节点 js 应用程序连接到 sqlite 数据库。 I saw its documentation for how to use prepared statements here but it is very brief and I cannot understand how to use it for my use case.我在这里看到了有关如何使用准备好的语句的文档,但它非常简短,我无法理解如何将它用于我的用例。

Lets say I have an sql string like this:假设我有一个像这样的 sql 字符串:

const sql = "INSERT INTO tbl(name) VALUES (?)"

So as per the documentation guess I should first create a statement and then use bind to populate it:因此,根据文档猜测,我应该首先创建一个语句,然后使用 bind 来填充它:

const stmt = await db.prepare(sql)
stmt.bind({? : "John"})

Is this the right way to do this?这是正确的方法吗? Also once I have created the Prepared statement how am I supposed to run this.同样,一旦我创建了 Prepared 语句,我应该如何运行它。 All the examples mentioned in the docs are select statements, but if it is an insert statement I suppose stmt.get() or stmt.all() method are not correct as there is no result set to return here.文档中提到的所有示例都是 select 语句,但如果它是插入语句,我认为 stmt.get() 或 stmt.all() 方法不正确,因为这里没有返回结果集。 How then am I supposed to do this?那我该怎么做呢?

I don't know the sqlite library too well, but the following example from the documentation performs a parameterised INSERT statement:我不太了解sqlite库,但是文档中的以下示例执行了参数化的INSERT语句:

const result = await db.run('INSERT INTO tbl(col) VALUES (:col)', {
  ':col': 'something'
})

I think you're focusing on the phrase 'prepared statement' a little too much.我认为您过于关注“准备好的声明”这个短语。 Instead of looking only for this exact phrase, look for any use of parameters whose values are passed separately to the main SQL string.不要只寻找这个确切的短语,而是寻找任何参数的使用,这些参数的值分别传递给主 SQL 字符串。 The example above fits this: there is a parameter :col which appears in the SQL string and the value for it is provided in an object passed to db.run alongside the SQL string.上面的例子适合这个:有一个参数:col出现在 SQL 字符串中,它的值在 object 中提供,与 Z9778840A0100CB30C9822876741B05B 一起传递给db.run

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM