我有一个简单的 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)
您看到的错误,
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 (?,?)