gpt4 book ai didi

javascript - 如何传递并执行 mysql 查询?

转载 作者:行者123 更新时间:2023-11-29 10:43:00 25 4
gpt4 key购买 nike

我想知道如何执行 mysql 查询,以便客户端可以看到“用户注册:编号

服务器.js:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'kitsune',
connectionLimit: 50,
port: 3306 });

connection.connect(function(err) {
if (err) throw err;
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
module.exports = connection;

http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});

fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var countQuery = "SELECT Count(ID) AS NumberOfPenguins FROM Penguins"; console.log(countQuery);
connection.query(countQuery, function(err, rows) {
if (err) throw err;
console.log('Connected!');
});

var renderedHtml = ejs.render(content, {countQuery: countQuery});
res.end(renderedHtml);
});
}).listen(80);

index.html:

<html>
<head>
</head>
<body>
Users registered: <%= countQuery %>
</body>
</html>

这仅显示查询但不执行它。关于如何执行它有任何想法吗?

最佳答案

您确实执行了查询,但您从未对结果执行任何操作。结果是回调函数中传递的

connection.query(countQuery, function(err, rows) {
if (err) throw err;

var renderedHtml = ejs.render(content, {countQuery: rows});
res.end(renderedHtml);
});

关于javascript - 如何传递并执行 mysql 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45133400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com