Socket.io MySQL会话

时间:2014-11-15 16:32:15

标签: mysql node.js sockets express socket.io

如何在socket.io会话中存储和访问mysql insertId?

var mysql = require('mysql');
var express = require('express');
var app = express();
var router = express.Router(); 
var https = require('https').createServer( ssl_options, app);
var io = require('socket.io')( https );

io.on('connection', function(socket){

   socket.on('new user', function(data) {

      socket.username = data.username;

      var query = connection.query('INSERT INTO chat SET ?', {subject:'1',message:'2'}, function(err, result) {

         socket.chat_id = result.insertId;

      });

      console.log ( socket.username ) // Username
      console.log ( socket.chat_id ) // Nothing returns?

   });

});

2 个答案:

答案 0 :(得分:0)

我怀疑你的插入是否有效,所以它实际上没有插入值。我想你想把你的插件改成这样的东西。另外,添加错误测试

var query = connection.query('INSERT INTO chat (subject, message) VALUES (?, ?)', {subject:'1',message:'2'}, function(err, result) {
    if(err) {
        console.log(err.message);
        return;
    }
    socket.chat_id = result.insertId;
});

答案 1 :(得分:0)

与Chris一样,您的参数与查询所需的元素数量不匹配。第二个问题:通常第二个参数是值数组而不是对象。 第三个问题:您在查询返回值之前进行测试,因为您的console.log在匿名回调函数之外。

var query = connection.query('INSERT INTO chat (subject, message) VALUES (?, ?)', ['1','2'], function(err, rows) {
    socket.chat_id = result.insertId;
    console.log( socket.chat_id);
}