I have a javascript function which is intended to output a 0 if a mysql table doesn’t exist and a 1 if it does. But I have not been able to understand why it does not function as intended.
function TableExistsOrNot (checktable){
try{
console.log("the function was entered");
var sqlcheck = 'SELECT id FROM ?? ORDER BY id DESC LIMIT 1';
con.query(sqlcheck,[checktable],function (err, result) {
if (result > 0){
console.log(result);
console.log("table exists");
return 1;
}
if(result === undefined){
console.log("result was undefined");
return 0.0;
}
});
}
catch (err) {
console.log(err);
console.log("error locating table");
return 0;
}
}
When I console log the result it just says undefined. And if I try to assign the result of the function to a variable it also says undefined.
edit based on the feedback I have added code for async nature, installed and required express. But this has not solved the problem. See the code below. What is strange is console.log(a);
in the else statement is logging 5. But the last line console.log(datatablepresent);
which should be equal to ‘a’ is logging Promise { <pending> }
function checktable(tablename) {
try{
let sql = 'SELECT id FROM ?? ORDER BY id DESC LIMIT 1';
return new Promise((resolve, reject) => {
con.query(sql,[tablename],(err, result) => {
if (err) {
console.log("entered err");
}
else {
resolve(result);
console.log("entered else");
var a = result[0].id;
if (a>1){
console.log(a);
return a;
}
}
});
});
}
catch (err) {
console.log(err);
console.log("error locating table");
//return 0;
}
}
app.get("/", async function (req, res) {
console.log("entered callback");
const result = await checktable();
res.send(result);
console.log(result);
});
datatablepresent = checktable('beta5');
console.log(datatablepresent);
2
Answers
Here is the right query to find out if a table exists. Use the table — actually the system view — named TABLES information_schema.
It’s too hard to issue a query and cope with a sometimes-expected error when you can just get a number. What you want to do is simply ask the system. And you’re presenting the name of the table as an ordinary string value to go into a placeholder.
You give the table name as the substitution parameter. The query always returns one row and one column. The column, named
table_exists
in the result set, has the value 1 if the table does exist, and 0 otherwise.Then you have to structure the query and error handler correctly, and handle the async nature of the query correctly. The easiest way to do that is with the mysql2 package and an async function.
Edit You can put all your Javascript code in an async function, like this.
Or you can do use a promises’ then clause to call async code from a non-async context:
You can simply check whether the table exists or not in the particular database just with
If the table exists, it will return:
If not, it will return:
So it can return 1 or 0 (exist or not) with the value of
result.length
.