Reputation: 1186
I'm learning Node.js, and I've decided to poke at node-mysql. I'm trying to insert some text, and its not working-when I query the relevant table, nothing is there. When I set a breakpoint and debug, the connection state says "disconnected." What am I doing wrong?
Node code:
socket.on('chat message', function(msg){
var connection = mysql.createConnection({
host: 'localhost',
user: 'XXXXX',
password: 'YYYYY',
database: 'chat'
});
connection.connect();
var objToday = new Date(),
weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
dayOfWeek = weekday[objToday.getDay()],
domEnder = new Array( 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th' ),
dayOfMonth = today + (objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder[objToday.getDate()] : objToday.getDate() + domEnder[parseFloat(("" + objToday.getDate( )).substr(("" + objToday.getDate()).length - 1))],
months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
curMonth = months[objToday.getMonth()],
curYear = objToday.getFullYear(),
curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
//var today = curHour + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + curMonth + " " + dayOfMonth + ", " + curYear;
var today = curYear+"-"+curMonth+"-"+dayOfMonth+" "+curHour+":"+curMinute+":"+curSeconds
var post={time: today, message: msg.message};
var query = connection.query('INSERT INTO messages SET ?', post, function(err, result) {
// Neat!
console.log(result);
});
//console.log(result);
io.emit('chat message', msg);
});
when i set a breakpoint right after connection.connect(), I look at connection in the watch window, and connection.state ="disconnected." I'm running WebStorm on a Mac. EDITED TO ADD: Rest of code
Upvotes: 0
Views: 290
Reputation: 106736
The actual connection to the database is made asynchronously, so it's not going to be connected right after connection.connect();
. If you just call connection.query(...);
it should implicitly connect and automatically execute the query upon connection.
Also on an unrelated note, you may wish to use a pool of database connections that you create before starting up your socket.io server instead of creating a new database connection on every single chat message event. This should help prevent someone from DoS'ing your database server (either intentionally or accidentally).
Upvotes: 1