如何从Deno的sqlite库获取对象数组,及查询无返回问题排查
实现方案
该需求完全可以实现,deno的sqlite库原生提供了返回键值对结构结果的API,不需要手动映射数组。
最简实现(无需预编译查询)
直接使用queryEntries方法,返回结果默认就是以查询字段名为属性的对象数组:
const users = db.queryEntries<{ id: number; email: string; hashed_password: string; }>('SELECT id, email, hashed_password FROM users WHERE email = ?', [body.email]); const user = users[0]; if (!user) { context.response.status = 400; context.response.body = { message: "User not found" }; return; } // 直接通过属性访问即可 const comparison = await bcrypt.compare(body.password, user.hashed_password);
预编译查询的正确写法
你调整后的代码查不到结果是因为三个错误:
prepareQuery的第二个参数不是查询入参,是可选的列配置项,你把参数写在这里属于传参位置错误- 查询返回3个字段,你定义的泛型元组只有2个类型,类型不匹配
- 查询入参需要传给
oneEntry方法,而不是prepareQuery
正确写法如下:
try { // 预编译仅传入SQL语句,泛型依次定义元组返回类型、对象返回类型 const query = db.prepareQuery< [number, string, string], { id: number; email: string; hashed_password: string } >("SELECT id, email, hashed_password FROM users WHERE email = ?"); // 查询参数传入oneEntry方法 const user = query.oneEntry([body.email]); if (!user) throw new Error("用户不存在"); console.log('user: ', user); // 后续业务逻辑 } catch(err) { console.error(err); context.response.status = 400; context.response.body = { message: "User not found" }; return; }
内容的提问来源于stack exchange,提问作者chovy
相关产品推荐
相关产品推荐

