Answer the question
In order to leave comments, you need to log in
How to pull data from a database query using the connection.query function in node.js (except for conslole.log)?
Colleagues, I am not a programmer, but it is very necessary for production needs.
I understand that there is a similar question, but I can’t understand the answers in it, and in general,
the understanding of callback functions has not been given to me for the 4th day.
Tell me I use node-webkit with the mysql module installed
in the example I took something like this:
index.html
!DOCTYPE html>
<html>
<head>
<title>Hello World2!</title>
<script>
function bodyOnLoad(){
misc=require('./mysql.js');
}
</script>
</head>
<body onload="bodyOnLoad();" >
</body>
</html>
var mysql = require('mysql');
var connection = mysql.createConnection({
database : 'techtrain',
user : 'root',
password : ''
});
connection.connect();
connection.query('SELECT * FROM `answer` WHERE `question_id` = 2', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].answer_name);
});
connection.end();
Answer the question
In order to leave comments, you need to log in
You need to understand the mechanism for exporting the result of a function from within to the external environment.
1. Documentation of the nodejs API "modules"
2. Explanations on Habré
And in the html file, the DOM API innerHTML
var mysql = require('mysql');
var connection = mysql.createConnection({
database : 'mysql',
user : 'root',
password : 'toor'
});
var x={};
var query = function(){
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
x = rows[0].solution;
});
connection.end();
};
var answer = function(){
return x;
};
module.exports.query = query;
module.exports.answer = answer;
<!DOCTYPE html>
<html>
<head>
<title>Hello World2!</title>
<script>
var mysql = require('./mysql.js');
function bodyOnLoad(){
mysql.query();
};
function getAnswer(){
document.getElementById("answer").innerHTML = mysql.answer();
}
</script>
</head>
<body onload="bodyOnLoad();">
<div id="answer" onClick="getAnswer;">Click me</div>
</body>
</html>
app.get('/page', function(req, res) {
connection.query("SELECT * FROM `table`", function(err, result) {
res.render('index.html', { object: result });
});
});
Colleagues, but at least someone can give an explicit answer, how can I extract and process the
"rows[0].answer_name" key in this example with anything other than console.log? I've been wasting my time for 5 days now
Read more about closures and callback functions (closure, callback)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question