Node.js SQL Server代码似乎是错误的,但是仍然有效吗?

阿玛塔夫

尝试按属性(id,user_name,foo,bar等)选择条目;

这是我的套接字代码;

socket.on('database attribute', function(msg) {
		queryDriver.getAllEntriesByAttribute(gatheringstable, 'user_name', 'john', function(err, gatherings) {
			console.log(gatherings);
			io.emit('database attribute', gatherings);
		});
	});

这是我的数据库驱动程序代码;

QueryDriver.prototype.getAllEntriesByAttribute = function(table, attribute, value, callback) {
	this.dbclient.query('SELECT * FROM ' + table + ' WHERE ' + attribute + '=' + value, function(err, result) {
		if(err) {
			callback(err);
		}
		else {
			callback(null, result.rows);
		}
	});
};

如果我们看一下此SQL命令的典型语句,它看起来像"SELECT * FROM table WHERE attribute='value';"这将从数据库中拉出具有'john'的'user_name'属性的条目。

这在我的作品 'heroku pg:psql' daemon.

由于某些原因,这在我的代码中不起作用,除非我更改命令中“值”和“属性”的位置。像这样;

socket.on('database attribute', function(msg) {
		queryDriver.getAllEntriesByAttribute(gatheringstable, 'john', 'user_name', function(err, gatherings) {
			console.log(gatherings);
			io.emit('database attribute', gatherings);
		});
	});

然后,它将对我的heroku实现工作得很好,我可以调用它并获取它,[{"id":1,"user_name":"john"}]但是它拒绝在我的“ heroku pg:psql”守护程序中工作。

我是否发现了世界上最良性的SQL错误?

现实会崩溃吗?

为什么这样做相反?"user_name"="john"是您将其称为ACTUAL的实际方法,但它"john"="user_name"是唯一对我有效的正确方法。

阿玛塔夫

我通过执行以下操作修复了该问题。

在守护程序内部,我测试了两个命令:

SELECT * FROM test_table WHERE 'user_name' = 'john'

其中返回“ null”

SELECT * FROM test_table WHERE user_name = 'john'

其中返回“ 1列”

虽然Vao Tsun的答案很接近,但实际上并不能解决这个特定问题,但是它给了我关于如何做的巧妙提示。

正确的实现是这样;

QueryDriver.prototype.getAllEntriesByAttribute = function(table, attribute, value, callback) {
    this.dbclient.query('SELECT * FROM ' + table + ' WHERE ' + attribute + '=' + "'" + value + "'", function(err, result) {
        if(err) {
            callback(err);
        }
        else {
            callback(null, result.rows);
        }
    });
};

等同于执行第二个命令,

SELECT * FROM test_table WHERE user_name = 'john'

因此,属性一定不能用引号引起来,值一定不能用引号引起来。

Vao Tsun的答案很接近,但仅当您未引用文本值时才有效。如果要查找带有文本值的列,则不得使用引号将属性转义。您必须转义该值。

因此,

[{"id":1,"user_name":"john"}]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章