You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中npm sqlite库预编译语句的使用及执行疑问

Node.js sqlite库预编译插入语句正确用法
  • 绑定参数的正确方式
    你当前的stmt.bind({? : "John"})写法有误。针对SQL中的?位置占位符,直接传入值数组即可;如果想用命名占位符,需要先修改SQL语句的占位符格式。
    示例:

    // 位置占位符(?)的绑定
    stmt.bind(["John"]);
    
    // 命名占位符的写法(更易读)
    const sql = "INSERT INTO tbl(name) VALUES (:name)";
    const stmt = await db.prepare(sql);
    stmt.bind({ name: "John" });
    
  • 插入语句的执行方法
    无结果集的插入、更新、删除操作,需要使用stmt.run()方法,它会返回包含影响行数、插入记录ID等信息的对象。完整示例:

    const sql = "INSERT INTO tbl(name) VALUES (?)";
    const stmt = await db.prepare(sql);
    try {
      // 可以直接把参数传给run,省略单独的bind步骤
      const result = await stmt.run("John");
      console.log(`成功插入${result.changes}条记录,新记录ID:${result.lastID}`);
    } finally {
      // 必须调用finalize释放预编译语句占用的资源
      await stmt.finalize();
    }
    

    如果不需要复用预编译语句,也可以直接用db.run()简化代码,它会自动处理预编译和资源释放:

    const result = await db.run("INSERT INTO tbl(name) VALUES (?)", "John");
    console.log(`成功插入${result.changes}条记录,新记录ID:${result.lastID}`);
    

内容的提问来源于stack exchange,提问作者Chandrachur Mukherjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:57:24