MySQL NodeJs - 让 rows.each 工作的正确方法

标签 mysql node.js rows node-mysql2

当我寻找简单的例子时,每个人的风格似乎都很不同。我尝试了两种不同的风格,并遇到了两个不同的问题。在下面的代码中,我已经确定了代码的来源以及注释中出现的错误。我注释掉或取消注释每个部分并单独运行,但每个部分都有自己的错误。 “console.log(rows);”语句显示数据,因此查询本身正在运行并工作。

// get the client
const mysql = require('mysql2');
const dashline = '---------------------------------';  

console.log (dashline); 
console.log ("Starting test"); 

// create the connection to database
const connection = mysql.createConnection({
  host: 'myhost',
  user: 'myuser',
  password: 'mypass',
  database: 'myDatabase'

});


console.log ("Got the database connection"); 


query = "select ID, user_nicename, user_email from wp_users where user_login = 'admin' limit 3 ";

console.log ("Starting query"); 

// Attempt 1
/*
connection.query(query, function(err, rows, fields){
  if (err) throw err;

  // from: https://html5hive.org/node-js-quickies-working-with-mysql/ 
  // error: SyntaxError: Unexpected token { (on the rows.each line below) 
  rows.each(element, index) {
    console.log(element.ID+ " " + element.user_nicename);
  }
  console.log (dashline); 
  console.log ("Query End"); 
  process.exit();   // Else Node hangs and must hit cntl-break to exit 

});
*/




// Attempt 2 

connection.query(query, function(err, rows, fields){
  if (err) throw err;
  console.log(rows); 
  // Roughly based on example on this page: 
  // https://datatables.net/reference/api/each()
  // TypeError: rows.each is not a function 
  rows.each( function(element, index) {
    console.log(element.ID + " " + element.user_nicename);
  });
  console.log (dashline); 
  console.log ("The end"); 
  process.exit();   // Else Node hangs and must hit cntl-break to exit 
});

最佳答案

方法.each对于数组不存在,您应该使用 .forEach(function (element, index) {...})相反

关于MySQL NodeJs - 让 rows.each 工作的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57455356/

相关文章:

node.js - 如何在node js中获取表单数据并查询mongodb

javascript - js异步读取文件

javascript - 名字和姓氏在 mongoDB 中组合搜索

javascript - 在单独的表格中按类别或 ID 突出显示 2 行

python - 读取同一行中多个项目的项目

c - 查找矩阵中的最大元素

MySQL:尝试理解 SELECT 查询来获取附近的位置

mysql - MySql TEXT/BLOB 类型的最大声明列长度是多少?

mysql - 如何杀死mysql进程

php - 警告 : mysql_fetch_array(): supplied argument is not a valid MySQL Result in line 40