Myslq2 Nodejs数据库查询返回旧数据
每次我运行这段代码时,我的 id 变量总是有一个不再存在于数据库中的值,我尝试重新启动数据库和我的计算机但无济于事,我做错了什么?
const mysql = require('mysql2');
const Discord = require('discord.js');
let bot;
let token;
let id = '';
let botName;
// create the connection to database
const c = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'monkeybot'
});
//grab initial data from database
c.execute("SELECT * FROM `info`", (err, results, fields) =>{
token = results[0].token;
id = results[0].self_id;
c.query("SELECT * FROM `people`", (err, results, fields) =>{
console.log(results)
botName = results[0];
console.log("token: " + token);
console.log("id: " + id);
console.log("name: " + botName);
console.log("-----------------------");
});
});```
every time I run this code, my id
variable always has a value that is not in the database anymore, I have tried restarting the database and my computer to no avail, what am I doing wrong?
const mysql = require('mysql2');
const Discord = require('discord.js');
let bot;
let token;
let id = '';
let botName;
// create the connection to database
const c = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'monkeybot'
});
//grab initial data from database
c.execute("SELECT * FROM `info`", (err, results, fields) =>{
token = results[0].token;
id = results[0].self_id;
c.query("SELECT * FROM `people`", (err, results, fields) =>{
console.log(results)
botName = results[0];
console.log("token: " + token);
console.log("id: " + id);
console.log("name: " + botName);
console.log("-----------------------");
});
});```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你能发布你得到的console.log吗,因为我最初的假设是“id”和令牌是未定义的,如果是这种情况,则将承诺与.then链接起来,或者使用更简单的异步等待。在任何情况下,您尝试查询两个不同的表,并且我假设使用两个查询中的数据,如果您可以将其编写为表之间的 JOIN(如果它们具有主键和外键关系),那就更好了。另一种方法是创建两个函数,每个函数查询一个表并返回结果,这样您就可以直接使用它们。
Could you post the console.log you are getting, because my initial assumption is that the 'id' and token are comng as undefined, if thats the case chain the prommises whit a .then or use the much simpler async await. In any case you are trying to query two different tables and i asume use the data from both queries, it would be better if you can write it as a JOIN between the tables if they have a primary and foregin key relation. A nother way to go would be to make two functions that each queries a table and return the result, that way you can use them down the line.