2017-04-25 140 views
0

我正在開發一個使用nodejs和mysql的web應用程序。 MySQL連接工作正常,但查詢不是擅長的,也不顯示任何錯誤。我的代碼如下所示。請幫助我。MySQL插入不工作在節點js

var mysql = require("mysql"); 
var con = mysql.createConnection({ 
host: "localhost", 
user: "root", 
password: "", 
database : "db" 
}); 

con.connect(function(err){ 
if(err){ 
     console.log('Error connecting to Db'); 

    return; 
} else { 


var time = Date.now(); 
var post = {userphone: "user", senderphone: "to1", message: "msg", time:time};    
var query = con.query('INSERT INTO chat SET ?', post, function(err, result) { 
    console.log('db added'); 
    console.log(query.sql); 
      }); 
     console.log('Connection established'); 
    } 
}); 

con.end(function(err) { 
    // The connection is terminated gracefully 
    // Ensures all previously enqueued queries are still 
    // before sending a COM_QUIT packet to the MySQL server. 
}); 
+0

插套是不是標準的SQL – modsfabio

+0

我用VALUES而不是SET但同樣的問題。 – joe

+0

你有沒有檢查err變量中會發生什麼?我的意思是在這裏 - query = con.query(.. INSERT QUERY ..,post,function(err,result){if(err){throw err;} else {....} –

回答

1

如果您嘗試打印err在連接它顯示:

~/Documents/src : $ node testInsert.js 
Connection established 
{ [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false } 
db added 
INSERT INTO chat SET `userphone` = 'user', `senderphone` = 'to1', `message` = 'msg', `time` = 1493132496360 

顯然你的數據庫連接是越來越執行查詢之前關閉。你需要的是緊密連接塊進入查詢塊,迫使它是這樣的查詢後執行:

con.connect(function(err){ 
    console.log('Connection established'); 
    if(err){ 
     console.log('Error connecting to Db'); 
     return; 
    } else { 
    var time = Date.now(); 
    var post = {userphone: "user", senderphone: "to1", message: "msg", time:time};    
    var query = con.query('INSERT INTO chat SET ?', post, function(err, result) { 
     if(err) console.log(err); 
     console.log('db added'); 
     console.log(query.sql); 
     con.end(function(err) { 
      // The connection is terminated gracefully 
      // Ensures all previously enqueued queries are still 
      // before sending a COM_QUIT packet to the MySQL server. 
     }); 
    }); 
    } 
}); 

,當我跑它插入成功:

~/Documents/src : $ node testInsert.js 
Connection established 
db added 
INSERT INTO chat SET `userphone` = 'user', `senderphone` = 'to1', `message` = 'msg', `time` = 1493132632444 
mysql> SELECT * FROM chat; 
+-----------+-------------+---------------------+---------+ 
| userphone | senderphone | time    | message | 
+-----------+-------------+---------------------+---------+ 
| user  | to1   | 0000-00-00 00:00:00 | msg  | 
+-----------+-------------+---------------------+---------+ 
1 row in set (0.00 sec)