NodeJS SQLITE_RANGE:列索引超出范围:SQLite

5jdjgkvh  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(199)

我有一个简单的sqlite SELECT查询如下,

db.js

const dbFile = path.resolve(__dirname, ../disk.db);
const dbExists = fs.existsSync(dbFile);

if (!dbExists) {
   console.log("database file doesn't exist")
   fs.openSync(dbFile, 'w');
}

console.log("database file exists")

exports.db= new sqlite3.Database(dbFile, sqlite3.OPEN_READONLY, (err) => {
  if (err) {
      console.error(err.message);
  }
  console.log(`Connected to disk database`);
});

query.js

const database= require("../db.js"); 
const studentDB = database.db;   

const rollNos = [12, 15];

const query = `Select * from Student where rollNo in (?)`

CommonQuery.executeQuery(query, rollNos, studentDB, cb)

common.query.js

class CommonQuery {

    excecuteQuery(query, param, db, cb) {
        db.serialize(() => {
          db.all(query, param,
            (error, rows) => {
              if (error) {                     // it throws error --- SQLITE_RANGE: column index out of range 
                console.log("error occured in executing query !", query, error);
                return cb(error);
              }
    
              return cb(null, rows);
            })

        });
    
      }
    }
}

如果我在sqlite数据库编辑器中执行下面的查询,它工作正常

Select * from Student where rollNo in (12, 15)
xtfmy6hx

xtfmy6hx1#

你看到的错误
SQLITE_RANGE:列索引超出范围
通常意味着SQL查询中的占位符数量与您试图绑定的参数数量不匹配。
您需要为每个值生成占位符保持器。大概是这样的:

SELECT * FROM Student WHERE rollNo IN (?, ?)

你可以试试这样的方法:

const rollNos = [12, 15];
const placeholders = rollNos.map(() => '?').join(',');
const query = `SELECT * FROM Student WHERE rollNo IN (${placeholders})`;
console.log(query)

// Output: SELECT * FROM Student WHERE rollNo IN (?,?)

相关问题