简体   繁体   English

连接数据库时出错

[英]Error when connecting to database

I'm doing a bot with the coin system and when you try to connect it to database gets this error. 我正在用硬币系统做一个机器人,当您尝试将其连接到数据库时遇到此错误。
Code: 码:

const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
const sql = require("sqlite");
const db = sql.open('./coin.sqlite', { Promise });

db.get(`SELECT * FROM coins WHERE userId = [message.author.id]`).then(row => {
  if (!row) { // Can't find the row.
    db.run("INSERT INTO coins (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
  } else {  // Can find the row.
    let curAmt = Math.floor(Math.random() * 5) +0.3 (row.coins + curAmt);
    if (curAmt > row.coins) {
      row.coins = curAmt;
      db.run(`UPDATE coins SET coins = ${row.coins + curAmt}, WHERE userId = [message.author.id]`);
    }
    db.run(`UPDATE coins SET coins = ${row.coins + curAmt} WHERE userId = [message.author.id]`);
  }
}).catch(() => {
  console.error; // Log those errors.
  db.run("CREATE TABLE IF NOT EXISTS coins (userId TEXT, coins INTEGER)").then(() => {
    db.run("INSERT INTO scores (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
  });
});

bot.login(tokenfile.token);

Error: 错误:

db.get(`SELECT * FROM coins WHERE userId = [message.author.id]`).then(row => {
   ^

TypeError: db.get is not a function
    at Object.<anonymous> (C:\Users\Илья\Desktop\JyxoBot\Jyxo\index.js:54:4)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
[nodemon] app crashed - waiting for file changes before starting...

The bot doesn't run, I don't understand what is the problem, everything seems right to me. 机器人无法运行,我不明白问题出在哪里,一切似乎对我来说都是正确的。

sql.open('./coin.sqlite', { Promise });

Returns a promise, so when you run db.get(), you are actually trying to use that method on an unresolved promise. 返回一个诺言,因此当您运行db.get()时,实际上是在尝试对未解决的诺言使用该方法。

What you need to do is: 您需要做的是:

const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
const sql = require("sqlite");
const db = sql.open('./coin.sqlite', { Promise });

sql.open('./coin.sqlite', { Promise })
    .then((db) => {
        runApp(db);               
    }).catch((err) => {
        console.log(err);
        process.exit(1);
    });

const runApp = (db) => {
    client.on("message", message => {
        if (message.author.bot) return;
        if (message.channel.type !== "text") return;
        if (message.content.startsWith("ping")) {
            message.channel.send("pong!");
        }
        db.get(`SELECT * FROM coins WHERE userId = ${message.author.id}`).then(row => {
            if (!row) { // Can't find the row.
                db.run("INSERT INTO coins (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
            } else {  // Can find the row.
                let curAmt = Math.floor(Math.random() * 5) +0.3 (row.coins + curAmt);
                if (curAmt > row.coins) {
                    row.coins = curAmt;
                    db.run(`UPDATE coins SET coins = ${row.coins + curAmt}, WHERE userId = ${message.author.id}`);
                }
                db.run(`UPDATE coins SET coins = ${row.coins + curAmt} WHERE userId = ${message.author.id}`);
            }
       }).catch(() => {
           console.error; // Log those errors.
           db.run("CREATE TABLE IF NOT EXISTS coins (userId TEXT, coins INTEGER)").then(() => {
               db.run("INSERT INTO scores (userId, coins) VALUES (?, ?)", [message.author.id, 0]);
           });
       });

       bot.login(tokenfile.token);

    };
};

This will wait for the promise to resolve and return the db object. 这将等待承诺解决并返回db对象。 See the examples at: https://www.npmjs.com/package/sqlite for more details. 有关更多详细信息,请参见https://www.npmjs.com/package/sqlite上的示例。

You also needed to put the code in the discord client's message handler as shown in the guide: https://anidiotsguide_old.gitbooks.io/discord-js-bot-guide/coding-guides/storing-data-in-an-sqlite-file.html 您还需要按照指南中所示将代码放入不和谐客户端的消息处理程序中: https : //anidiotsguide_old.gitbooks.io/discord-js-bot-guide/coding-guides/storing-data-in-an-sqlite -file.html

I also separated out most of your app code into a function just to make it easier to read. 我也将您的大多数应用程序代码分离为一个函数,以使其易于阅读。 The db object returned from the promise is passed into this function so it can be used. 从promise返回的db对象将传递到此函数,以便可以使用它。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM