Reputation: 31
I am new to Node and have been using it for just over a week now, everything's fine until I tried to connect to a MySQL database and I'm having no luck.
I have installed the necessary files;
npm install mysql
and my code is as follows;
const mySQL = require('mysql');
const mySQLCon = mySQL.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "databaseName"
});
function connectTest() {
mySQLCon.connect(function(err) {
if(err){
console.log(err.code);
console.log(err.fatal);
}
});
console.log(mySQLCon.state);
sSQL = "SELECT sField FROM tblName WHERE iID = 1";
mySQLCon.query(sSQL, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
return;
}
if (rows.length > 0) {
console.log(rows[0].sField);
} else {
console.log("No Records found!");
}
});
mySQLCon.end(function(){
// The connection has been closed
});
}
connectTest()
I'm using;
console.log(mySQLCon.state);
To see what the state of the connection is and it says 'disconnected'.
I don't get any errors when this runs it just doesn't do anything.
The database is on a remote PC, however I am using the same credentials to successfully connect to the database in other ways from this computer without any problems (navicat).
I tried running the code on the local database computer to see if that was the issue and it did the same thing, didn't connect and no errors.
Any help would be appreciated because I am totally lost without any errors to guide me and I'm doing what I think is correct!
Thanks
Upvotes: 3
Views: 965
Reputation: 23495
There is two possibilities.
First of all, the connection is asynchronous, you should wait the connection to be explicitly over to do anything else.
Example:
mySQLCon.connect(function(err) {
if(err){
console.log(err.code);
console.log(err.fatal);
return;
}
console.log(mySQLCon.state);
sSQL = "SELECT sField FROM tblName WHERE iID = 1";
mySQLCon.query(sSQL, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
return;
}
if (rows.length > 0) {
console.log(rows[0].sField);
} else {
console.log("No Records found!");
}
});
mySQLCon.end(function(){
// The connection has been closed
});
});
So the first possibility is that you never get any error because there is a timeout attached to the connection. So until the time is reached the function is going to hang.
It seems that you can change the timeout using the option connectTimeout: 1000000
.
Second possibility is that it actually connect, and because you have no console.log
telling you that you don't know. I refer you to the asynchronous problem I described to you just before.
Upvotes: 2