Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi row insert using Knex.js

Am trying to build an multi-row insert query using Knex.js

My post request contains a variable which is formatted in the following format : [{addon_name:'sugar'},{addon_name:'milk'}]

My DB table has only one column namely addon_name

My knex query in my node application goes as follows

knex(`<table_name>`).insert(req.body.`<param_name>`))

expected op

insert into `<tablename>`(`addon_name`) values (sugar), (milk);

but the code dosn't work. Any comments ?

Error Details

{ [Error: insert into `table_name` (`0`, `1`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `2`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, `27`, `28`, `29`, `3`, `30`, `31`, `32`, `33`, `34`, `35`, `36`, `37`, `38`, `39`, `4`, `40`, `41`, `5`, `6`, `7`, `8`, `9`) values ('[', '{', 'm', 'e', ':', '\'', 's', 'u', 'g', 'a', 'r', '\'', 'a', '}', ',', '{', 'a', 'd', 'd', 'o', 'n', '_', 'n', 'd', 'a', 'm', 'e', ':', '\'', 'm', 'i', 'l', 'k', '\'', 'd', '}', ']', 'o', 'n', '_', 'n', 'a') - ER_BAD_FIELD_ERROR: Unknown column '0' in 'field list']
  code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlState: '42S22',
  index: 0 }
like image 505
riceplatereddy Avatar asked Oct 05 '15 17:10

riceplatereddy


People also ask

What is KNEX transaction?

Transactions are handled by passing a handler function into knex. transaction . The handler function accepts a single argument, an object which may be used in two ways: As the "promise aware" knex connection. As an object passed into a query with and eventually call commit or rollback.

What does KNEX query return?

Knex returns an array for all queries, even if there is only one row returned. The name of the user can be accessed from user[0] .

What is KNEX NPM?

A SQL query builder that is flexible, portable, and fun to use! A batteries-included, multi-dialect (PostgreSQL, MySQL, CockroachDB, MSSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for Node. js, featuring: transactions. connection pooling.


2 Answers

Though this is an old question, I am replying here just for others who stumble upon this.

Knex now supports multi-row inserts like this:

knex('coords').insert([{x: 20}, {y: 30},  {x: 10, y: 20}])

outputs:

insert into `coords` (`x`, `y`) values (20, DEFAULT), (DEFAULT, 30), (10, 20)

There's also the batchInsert utility will inserts a batch of rows wrapped inside a transaction.

like image 129
Akshay Raje Avatar answered Oct 06 '22 02:10

Akshay Raje


req.body.<param_name> is always a string. Most probably this will work for you:

knex(table_name).insert(JSON.parse(req.body.param_name)));

What you are seeing in your error is Knex treating the string as an array of chars, trying to push it to the table.

In the error, the following:

values ('[', '{', 'm', 'e', ':', '\'', 's', ...

Is actually your string being broken down: [{me:\'s....

like image 41
Selfish Avatar answered Oct 06 '22 04:10

Selfish