无法使用node-mysql连接到MySQL数据库

时间:2014-07-28 22:21:04

标签: node.js node-mysql

我正在学习Node.js,我决定在node-mysql上学习。我正在尝试插入一些文本,并且它不起作用 - 当我查询相关表时,没有任何内容。当我设置断点并进行调试时,连接状态显示为“已断开连接”。我做错了什么?

节点代码:

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);

    });

当我在connection.connect()之后立即设置断点时,我会在监视窗口中查看连接,并且connection.state =“disconnected”。我在Mac上运行WebStorm。  编辑添加:其余代码

1 个答案:

答案 0 :(得分:1)

与数据库的实际连接是异步进行的,所以在 connection.connect();之后它不会立即连接。如果您只是调用connection.query(...);,它应该隐式连接并在连接时自动执行查询。

另外,在不相关的说明中,您可能希望在启动socket.io服务器之前使用您创建的数据库连接池,而不是在每个单独的聊天消息事件上创建新的数据库连接。这应该有助于防止有人(无论是有意还是无意)使用DoS数据库服务器。