【问题标题】:Discord.JS | TypeError: Cannot read property 'run' of null不和谐.JS | TypeError:无法读取 null 的属性“运行”
【发布时间】: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


【解决方案1】:

将我的评论变成一个完整的答案:

您没有返回要使用的数据库驱动程序,而是在 SQLite 模块本身上使用它。尝试返回一个连接句柄,并将其用于您的查询。您必须先等待数据库连接承诺解决,因此假设您支持 async/await,您可以执行以下操作:

const Discord = require("discord.js");
const sql = require("sqlite");
const dbProm = sql.open("./warnings.sqlite", {Promise});
const db = await dbProm;

   db.get(`SELECT * FROM warnings WHERE userId ="${message.author.id}"`).then(row => {
    if (!row) {
        db.run("INSERT INTO warnings (userId, level) VALUES (?, ?)", [message.author.id, 1]);
      console.log(row.level);
    } else {
        db.run(`UPDATE warnings SET level = ${row.level + 1} WHERE userId = ${message.author.id}`);
      console.log(row.level);
    }
  }).catch(() => {
    db.run("CREATE TABLE IF NOT EXISTS warnings (userId TEXT, level INTEGER)").then(() => {
        db.run("INSERT INTO warnings (userId, level) VALUES (?, ?)", [message.author.id, 1]);
      });
  });

【讨论】:

    【解决方案2】:

    我记得以前用过这个。

    我查看了我的旧代码,除了打开数据库的 {Promise} 之外,所有代码都是一样的。尝试删除该视图,因为您不使用承诺并且它不是 [better-]sqlite3

    sql.open("./warnings.sqlite")
    

    【讨论】:

    • 他们的代码示例中有承诺。 NPM 上的 sqlite 包装器确实提供了 Promise 支持。
    • 对不起,我一定没有把我的意思说清楚。我曾经并且现在仍然为 Discord 机器人编写代码。我的旧代码与他正在做的事情大致相同,除了 {Promise} 的事实之外,所有内容(当然是伪代码)都相同。我的是旧代码,所以我可以看看这是否可能已经过时了。
    猜你喜欢
    • 2021-01-11
    • 2021-04-14
    • 2021-05-18
    • 1970-01-01
    • 2020-11-10
    • 2020-11-11
    • 2021-04-15
    • 2021-05-10
    • 1970-01-01
    相关资源
    最近更新 更多