Py学习  »  DATABASE

如何导出mysql查询返回的“result”?

Logan Luedtke • 5 年前 • 948 次点击  

我试图使用node js将MySql数据最终放置在HTML(实际上是ejs)页面中。

我一直在使用W3的node js示例中的以下代码。 https://www.w3schools.com/nodejs/nodejs_mysql_select.asp

我最终想做的是对“result”使用module.exports,并能够访问另一个文件中的数组。我发现这很难完成。

var mysql = require('mysql');

var con = mysql.createConnection({ 
    host: "localhost",
    user: "username", 
    password: "password", 
    database: "testdb" 
});

con.connect(function(err) {
    if (err) throw err; 
    con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err; 
    console.log(result); 
});

// This is what is logged to the console.

// [ RowDataPacket { name: 'Company Inc', address: 'Highway 37' }, 
  RowDataPacket { name: 'Sanitation', address: 'Highway 27' }, 
  RowDataPacket { name: 'Ice Cream', address: 'Highway 11' } ]

// Above works but it doesn't do what I need it to. 
// Below is explained what I need to happen.

var mysql = require('mysql');

var x; // x is undefined

var con = mysql.createConnection({ 
    host: "localhost", 
    user: "username", 
    password: "password", 
    database: "testdb" 
});

con.connect(function(err) { 
    if (err) throw err; 
    con.query("SELECT * FROM customers", 
    function (err, result, fields) { 
    if (err) throw err; 
    x = result; // If I do a 'console.log(x);' here I get the array above. 
    // If try to 'module.exports = result;' here, it is 
    // undefined in the receiving file. }); 
});

console.log(x); // x is undefined, even though result was stored in x.

我希望代码底部的'console.log(x);'返回数组,但它是未定义的。这使我认为“con.query”中的任何内容都是本地的。如果是这样的话,我考虑使用“模块”。函数中的exports=result',但这也会在接收文件中返回未定义的变量。如果有人知道为什么会这样,或者有解决办法,我将非常感谢你的建议:)

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49809
 
948 次点击  
文章 [ 2 ]  |  最新文章 5 年前