Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

javascript - Query of MySQL database it does not work correctly with if conditional?

I want to select value from MySQL database, and if the value equal to wait then print something. It is simple thing, but the conditional it does not work correctly.

code:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'DAGtest2'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Database Connected!');
});

connection.query("SELECT `message` FROM `counter` LIMIT 1", (err, check) => {
    if(err) throw err;
    console.log(check);

    if (check['message'] === "wait"){
        console.log("waiting....");

    } else {
        console.log("start counter...."); 
    }
});

output:

Database Connected!
[ RowDataPacket { message: 'wait' } ]
start counter....

and if I delete the wait message is still show me the same output:

Database Connected!
[]
start counter....

I have tried to use unequal conditional:

if (check['message'] !== "wait"){
    console.log("waiting....");

} else {
    console.log("start counter...."); 
}

The output:

Database Connected!
[ RowDataPacket { message: 'wait' } ]
waiting....

and If I delete the wait as well:

Database Connected!
[]
waiting....

The correct output I want is when message is equal to wait, it must print waiting.... and else it must print start counter..... But the code it doesn't work correctly when I delete wait from table.

How could solve it, please?

question from:https://stackoverflow.com/questions/65871493/query-of-mysql-database-it-does-not-work-correctly-with-if-conditional

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Would reworking your sql statement to something more like this work for you?

SELECT message
CASE
    WHEN message = 'wait' THEN 'waiting....'
    ELSE 'start counter....'
END
FROM counter; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...