当我寻找简单的例子,每个人的风格似乎完全不同。 我试过2种不同的风格,并得到了2点不同的问题。 在下面的代码,我已经确定的代码,它会在注释错误的来源。 我注释掉或取消注释出各个部分,单独运行,但每一个都有它自己的错误。 在“执行console.log(行);”语句显示数据,所以查询本身运行和工作。
// 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
});