在node.js中运行mysql查询时,“字段列表”中的未知列错误

时间:2019-06-21 22:31:40

标签: mysql node.js

每当我尝试使用字符串作为值而不是其他数据类型时,我都在node.js中编写一个sql查询,该查询始终会给出错误:字段列表中的未知列 Query used to create table

CREATE TABLE directorAvailabilitiesInputForm (
ifID int auto_increment primary key,
sID int,
eID int,
url text,
FOREIGN KEY (sID) REFERENCES society(sID),
FOREIGN KEY (eID) REFERENCES recruitmentdrive(eID)
);

    fillDirectorAvailabilitiesInputFormTable: function (sID, eID, driveName, societyName) {
        var urlVariable = societyName + driveName;
        var number = 'sfsdfsd';
        console.log(societyName);
        console.log(driveName);
        console.log(urlVariable);
        conn.query('insert into directoravailabilitiesinputform(sID,eID,url) values (' +sID+ ',' +eID+ ',' + number + ');',
            function (err, results, fields) {
                if (err) throw err;
                else console.log('Updated ' + results.affectedRows + ' row(s).');
            });
    }

在所示的代码中,如果将变量号更改为4(即var number = 4;在第三行),查询工作正常。如果它是字符串(如代码中所示),则会出现错误消息。 / p>

不应存在任何错误消息,并且如果number是字符串,则代码应该可以正常运行。但是,上述错误消息仍然显示。

错误:

Error: Unknown column 'sfsdfsd' in 'field list'
    at Packet.asError (c:\Users\andre\Documents\GitHub\AWSprojectmalinproduction01\node_modules\mysql2\lib\packets\packet.js:684:17)
    at Query.execute (c:\Users\andre\Documents\GitHub\AWSprojectmalinproduction01\node_modules\mysql2\lib\commands\command.js:28:26)
    at Connection.handlePacket (c:\Users\andre\Documents\GitHub\AWSprojectmalinproduction01\node_modules\mysql2\lib\connection.js:455:32)
    at PacketParser.onPacket (c:\Users\andre\Documents\GitHub\AWSprojectmalinproduction01\node_modules\mysql2\lib\connection.js:73:18)
    at PacketParser.executeStart (c:\Users\andre\Documents\GitHub\AWSprojectmalinproduction01\node_modules\mysql2\lib\packet_parser.js:75:16)
    at Socket.<anonymous> (c:\Users\andre\Documents\GitHub\AWSprojectmalinproduction01\node_modules\mysql2\lib\connection.js:80:31)
    at Socket.emit (events.js:189:13)
    at Socket.EventEmitter.emit (domain.js:441:20)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)

1 个答案:

答案 0 :(得分:0)

问题出在查询中,您没有用引号'"括住值。

查询应为

const query = 'insert into directoravailabilitiesinputform(sID,eID,url) values ("' +sID+ '","' +eID+ '","' + number + '")'

使用模板文字好一些

const query = `insert into directoravailabilitiesinputform(sID,eID,url) values ("${sID}","${eID}","${number}")`;

但是您应该真正清理输入值并使用参数化查询。来自https://www.php.net/manual/es/timezones.php的文档:

const query = 'insert into directoravailabilitiesinputform(sID,eID,url) values (?, ?, ?)';
conn.query(query, [sID, eID, number], function (error, results, fields){ .. })