【发布时间】:2023-03-30 03:31:01
【问题描述】:
在尝试运行此代码时,我不断收到错误“TypeError: Cannot read property 'run' of null”。程序中的其他所有内容都运行良好,直到到达 sql.run 部分。
(注意:程序中还有处理所有 Discord.js 部分的其他代码,这里只有导致问题的部分)
const Discord = require("discord.js");
const sql = require("sqlite");
sql.open("./warnings.sqlite", {Promise});
sql.get(`SELECT * FROM warnings WHERE userId ="${message.author.id}"`).then(row => {
if (!row) {
sql.run("INSERT INTO warnings (userId, level) VALUES (?, ?)", [message.author.id, 1]);
console.log(row.level);
} else {
sql.run(`UPDATE warnings SET level = ${row.level + 1} WHERE userId = ${message.author.id}`);
console.log(row.level);
}
}).catch(() => {
sql.run("CREATE TABLE IF NOT EXISTS warnings (userId TEXT, level INTEGER)").then(() => {
sql.run("INSERT INTO warnings (userId, level) VALUES (?, ?)", [message.author.id, 1]);
});
});
【问题讨论】:
-
尝试更改
sql.open行以返回句柄,例如:const db = sql.open("./warnings.sqlite", { Promise });,然后使用db而不是sql进行get/run调用。 -
@BrandonAnzaldi 刚刚尝试过,得到了
TypeError: db.get is not a function -
啊,抱歉。您需要等待数据库连接承诺首先返回,或者使用
async/await,或者将代码放在数据库连接的then块中。请参阅 NPM 页面上的示例 npmjs.com/package/sqlite#how-to-use -
@BrandonAnzaldi 太棒了,谢谢!那行得通。
标签: javascript node.js discord.js