社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

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

Logan Luedtke • 5 年前 • 940 次点击  

我试图使用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
 
940 次点击  
文章 [ 2 ]  |  最新文章 5 年前