[英]SELECT not working in node.js
I'm trying to use a SELECT query on my SQL database using node.js, the SELECT query below should work but doesn't. 我正在尝试使用node.js在我的SQL数据库上使用SELECT查询,下面的SELECT查询应该可以,但是不能。 This is weird because I think this should work but it doesn't even enter the client.query function.
这很奇怪,因为我认为这应该可行,但它甚至都没有输入client.query函数。 I also copied my INSERT query which is actually working to show you my connection to the database works fine.
我还复制了INSERT查询,该查询实际上在向您展示我与数据库的连接是否正常。
What am I doing wrong in the SELECT query? 我在SELECT查询中做错了什么?
CreateConnection 创建连接
var mysql = require('mysql');
var client = mysql.createConnection({
host: '***',
user: '***',
password: '***',
database: '***'
});
SELECT Query (Not working) SELECT查询(不起作用)
function query(sql){
var returnvalue = "tempVal";
client.connect();
client.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
returnvalue = "doens't even enter function";
if (err) throw err;
returnvalue = rows[0].solution;
});
client.end();
return returnvalue;
}
INSERT Query (Is working) INSERT查询(正在运行)
function query(sql){
client.connect();
client.query('INSERT INTO users (username) VALUES("foo")');
client.end();
}
As .query()
is an asynchronous method, you won't be able to return
the value as the callback will be called after the return
is evaluated. 作为
.query()
是一个异步方法,您将无法return
的值作为后回调将被调用return
进行评估。
You'll have to continue the callback
pattern: 您必须继续执行
callback
模式:
function query(sql, callback) {
client.connect();
client.query(sql, function (err, rows, fields) {
if (err) {
callback(err);
else
callback(null, rows, fields);
});
client.end();
}
Correction: Seems client.end()
will allow current queries to finish before the connection actually closes. 更正:似乎
client.end()
将允许当前查询在实际关闭连接之前完成。
Closing the connection is done using
end()
which makes sure all remaining queries are executed before sending a quit packet to the mysql server.使用
end()
关闭连接,以确保在将退出数据包发送到mysql服务器之前执行所有剩余的查询。
Though, calling .end()
inside the callback is commonplace for many APIs as they will cut-off any pending actions. 不过,在许多API中,在回调函数中调用
.end()
很常见,因为它们会切断所有未决的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.