如何使用nodejs在SQL中调用行

时间:2018-07-03 03:51:51

标签: mysql node.js

我对Node.js或sql编码并不陌生,对使用Node.js的SQL来说还是很新

这是我的代码

var mysql = require('mysql');

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

message是聊天消息设置为的变量

 con.query("SELECT * FROM chatmessages WHERE InComingChat=", message, function (err,rows) {
            rows.forEach( (row) => {
            console.log("",row.InComingChat," is in ",row.OutComingChat);
            });
})

但显示TypeError:无法读取未定义的属性'forEach',应如何编写它以获取InComingChat中的值并在OutComingChat中输出该值?

1 个答案:

答案 0 :(得分:0)

con.query("SELECT * FROM chatmessages WHERE InComingChat=", message, function (err,rows) {
            rows.forEach( (row) => {
            console.log("",row.InComingChat," is in ",row.OutComingChat);
            });
})
  

rows是一个数组,其中查询中的每个语句都有一个元素:

尝试

con.query("SELECT * FROM chatmessages WHERE InComingChat=", message, function (err,rows) {
            rows[0].forEach( (row) => {
            console.log("",row.InComingChat," is in ",row.OutComingChat);
            });
})

read this-基于查询,这是他们定义的结构。

connection.query('SELECT 1; SELECT 2', function (error, results, fields) {
  if (error) throw error;
  // `results` is an array with one element for every statement in the query:
  console.log(results[0]); // [{1: 1}]
  console.log(results[1]); // [{2: 2}]
});