Sequelize JS插入错误

时间:2018-05-03 07:25:03

标签: mysql sql sequelize.js

我创建了一个sequelize raw query辅助函数,它将从我的mysql数据库中插入数据。

const addBudget = function(name, amount) {
  sequelize.query(
    'INSERT INTO budget (name, amount) VALUES(' + name + ',' + amount + ')', {
      type: Sequelize.QueryTypes.INSERT
    }
  ).then(function (data) {
    console.log('inserted STEAMER data---> ', data);     });
};

然后当我调用函数尝试在mysql数据库上插入一些数据时,看它是否将我的数据插入到记录中:

addBudget('Book', 100);

我收到了这个错误:

Executing (default): SELECT 1+1 AS result
Executing (default): INSERT INTO budget (name, amount) VALUES(Book,100)
Unhandled rejection SequelizeDatabaseError: Unknown column 'Book' in 'field list'
    at Query.formatError (/Users/mac/Documents/dudes/moira/node_modules/sequelize/lib/dialects/mysql/query.js:247:16)
    at Query.handler [as onResult] (/Users/mac/Documents/dudes/moira/node_modules/sequelize/lib/dialects/mysql/query.js:68:23)
    at Query.Command.execute (/Users/mac/Documents/dudes/moira/node_modules/mysql2/lib/commands/command.js:30:12)
    at Connection.handlePacket (/Users/mac/Documents/dudes/moira/node_modules/mysql2/lib/connection.js:502:28)
    at PacketParser.onPacket (/Users/mac/Documents/dudes/moira/node_modules/mysql2/lib/connection.js:81:16)
    at PacketParser.executeStart (/Users/mac/Documents/dudes/moira/node_modules/mysql2/lib/packet_parser.js:77:14)
    at Socket.<anonymous> (/Users/mac/Documents/dudes/moira/node_modules/mysql2/lib/connection.js:89:29)
    at Socket.emit (events.js:180:13)
    at addChunk (_stream_readable.js:274:12)
    at readableAddChunk (_stream_readable.js:261:11)
    at Socket.Readable.push (_stream_readable.js:218:10)
    at TCP.onread (net.js:581:20)

在将数据插入数据库时​​,不知道我在做什么?

3 个答案:

答案 0 :(得分:1)

这里的问题是你的价值应该用单引号或双引号括起来,但是你的代码会生成VALUES(Book,100);,应该是VALUES('Book','100');,为此

只需更改以下行:

'INSERT INTO budget (name, amount) VALUES(' + name + ',' + amount + ')'

有了这个:

`INSERT INTO budget (name, amount) VALUES('${name}','${amount}')`

答案 1 :(得分:1)

SQL仅允许将单引号字符串用作您的值。因此,这将不起作用:

'INSERT INTO budget (name, amount) VALUES("Book", 100)'

这也不会:

'INSERT INTO budget (name, amount) VALUES(Book, 100)'

假设您指示SQL读取整数形式的金额,这是插入值的正确方法:

'INSERT INTO budget (name, amount) VALUES('Book', 100)'

如果Book只是已经是字符串的变量,则还可以执行此操作以确保保留单引号规则:

`INSERT INTO budget (name, amount) VALUES('${Book}', 100)`

答案 2 :(得分:0)

你试过这个:

var sql = "insert into budget (name) values ()";
sequelize.execute(sql, function(error, result){
  console.log(result);
});

执行insert和update sql并获取更多信息