I am trying to insert array of objects into the SQL but getting the following error
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?)' at line 1",
sqlState: '42000',
index: 0,
sql: 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES ((19, 10, 2),?,?)'
This my testing array of object
var testData = [
{
productId: 10,
quantity: 2
}
]
I want to insert this object data into sql.
My current written code which is returning above error
let lastId = results.insertId
let orderedProductSql = 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES (?,?,?)'
var testData = [
{
productId: 10,
quantity: 2
}
]
let values = testData.reduce((o, a) => {
let ini = []
ini.push(lastId)
ini.push(a.productId)
ini.push(a.quantity)
o.push(ini)
return o
}, [])
connection.query(orderedProductSql, [values], (err, results) => {
if (err) {
return connection.rollback(_ => {
throw err
})
}
connection.commit(err => {
if (err) {
connection.rollback(_ => {
throw err
})
}
connection.release()
callBack(null, results)
})
})
How can I solve this ??
Try doing something like this:
connection.query( "INSERT INTO orderedproducts SET order_id=?, product_id=?, quantity=?" , [lastid, productid, quantity] ,
function(err, result) {
if(err) throw err;
});
You need to use SET to insert data into your mysql database.
Related
I want to insert into my table values which I get from my front.
so. I have
const Workers = function (workers) {
this.id = workers.id,
this.workers = workers.workers,
this.room = workers.room,
this.team = workers.team,
this.city = workers.city,
this.hotel_name = workers.hotel_name,
this.address = workers.address
};
Workers.create = (newWorkers, result) => {
sql.query(`INSERT INTO rooms_split (workers, room, hotel_name, address, createdAt, updatedAt) VALUES( ? , ? , ? , ?, DEFAULT, DEFAULT )`,
[newWorkers.workers, newWorkers.room, newWorkers.hotel_name, newWorkers.address], (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created splitted room: ", {
id: res.insertId,
...newWorkers
});
result(null, {
id: res.insertId,
...newWorkers
});
});
};
And there is my controller
exports.create = (req, res) => {
console.log("body " + JSON.stringify(req.body));
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
const workers = new Workers({
workers: req.body.workers,
room: req.body.room,
hotel_name: req.body.hotel_name,
address: req.body.address
});
Workers.create(workers, (err, data) => {
if (err)
res.status(500).send({
message: err.message || "Some error occurred while creating the Alias."
});
else res.send(data);
});
}
Output from
console.log("body " + JSON.stringify(req.body));
is
body {"workers":["John Snow","Juri Boyka"],"room":"45","hotel_name":"Test Hamburg","address":"Hamburg 5, test Strase"}
and it looks fine but when is time to insert it into table I got error
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Juri Boyka', `room` = '45', `team` = NULL, `city` = NULL, `hotel_na' at line 1",
sqlState: '42000',
index: 0,
sql: "INSERT INTO rooms_split SET `id` = NULL, `workers` = 'John Snow', 'Juri Boyka', `room` = '45', `team` = NULL, `city` = NULL, `hotel_name` = 'Test Hamburg', `address` = 'Hamburg 5, test Strase'"
}
I kniw what this error means but I have no idea why when I want to make query nodejs(?) separates my value so instead ['something','something2'] I got 'something', 'something2' and he is right that there are not enough columns
Change
[newWorkers.workers, newWorkers.room, newWorkers.hotel_name, newWorkers.address]
to
[newWorkers.workers.join(), newWorkers.room, newWorkers.hotel_name, newWorkers.address]
since the workers data type in MySQL is varchar. Therefore, you'll need to stringify your incoming workers array
Im trying to insert user data into my mysql database but Im getting this error " sql: 'SELECT * FROM users WHERE undefined = ?' "
Here is my code :
find: function(user = null, callback) {
//if the user variable is defined
if(user) {
var field = Number.isInteger(user) ? 'id' : 'email';
}
// prepare the sql query
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result){
if(err) throw err;
if(result.length){
callback(result[0]);
} else {
callback(null);
}
});
},
When I try to run a query I am getting 500 Internal Error. I want to insert query2 result to query as a data.
Query:
exports.create = async (req, res) => {
try {
const connection = await mysql.createConnection(config.mysql.credentials);
var query2='select MAX(orders) from pdb_product';
const query = `insert into pdb_product (product_code, description, active, third_party,
orders) values ("${req.body.product_code}", "${req.body.description}", ${(req.body.active == 'on' ? 1 : 0)}, ${(req.body.third_party == 'on' ? 1 : 0)}, ${query2});`;
await connection.query(query);
res.redirect('/products');
} catch (e) {
utils.error500(req, res, e.message);
}
};
The error I am getting:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select MAX(orders) from pdb_product)' at line 1
How can I resolve this?
You are missing a '(' bracket before the query2 parameter:
const query = `insert into pdb_product (product_code, description, active, third_party,
orders)
values ("${req.body.product_code}",
"${req.body.description}",
${(req.body.active == 'on' ? 1 : 0)},
${(req.body.third_party == 'on' ? 1 : 0)},
(${query2}));`;
i have a simple insert query that looks like that:
let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"')";
connection.query(sql, (err, result) => {
if(err) {
res.status(500);
} else {
res.send(result) // we have here an object that has only the inserted id
}
});
which i really want is getting the inserted row data not just the id without making another select query to get them.
is there is a way to make that happens in one query?
If you are using:
// include mysql module var mysql = require('mysql');
The mysql module won't return data on the insert's query. It's returning:
Number of rows affected, Number of records affected with the warning, Message
If you wanna get data that you inserted, you should use a query builder or ORM like Sequelize. Sequelize Documentation.
You can get last inserted id using the code below:
SQLconnnection.query(sql, (err, result) => {
if(err) {
console.error(err);
} else {
console.log(result) ;
/*Output=>{affectedRows: 1
changedRows: 0
fieldCount: 0
insertId: 1 =>Last inserted ID Here
message: ""
protocol41: true
serverStatus: 2
warningCount: 0}*/
console.log(result.insertId);//=>last inserted id get
}
});
You can use this to retrieve the
let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"') ; SELECT * FROM users WHERE id = SCOPE_IDENTITY()";
connection.query(sql, (err, result) => {
if(err) {
res.status(500);
} else {
res.send(result) // we have here an object that has only the inserted id
}
});
SCOPE_IDENTITY() Returns the last identity value inserted
This is my use case.
First I insert data to the customer table.
Then I get the insertId for the customer.
Then I try to insert data into address table using that id.
async function createCustomer(req, res, next) {
const customer = {
type: req.body.type,
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email
};
const first_line = req.body.first_line
console.log("Customer from front-end", customer);
try {
let query1 = "INSERT INTO customer_supplier SET ?";
connection.query(query1, customer, (error, results) => {
if (error) {
console.log("Error", error);
} else {
let userId = results.insertId;
let query2 = "INSERT INTO address (id,first_line) VALUES ?";
connection.query(query2, [userId, first_line], (error, results) => {
if (error) {
console.log("error in address ==================================", error)
} else {
res.json({
results: results
})
}
})
}
});
} catch (error) {
console.log("error from", error);
res.json({
error: error
});
}
}
But when I try to insert data into the address table,
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'36\' at line 1',
sqlState: '42000',
index: 0,
sql: 'INSERT INTO address (id,first_line) VALUES 36' }
Before put this question on stackoverflow I tried so many variations in my insert statement and nothing works for me.
How do I achieve this?
Your sql is not written correct,you need to add () to wrap the value
let query2 = "INSERT INTO address (id,first_line) VALUES (?,?)";
Below is the grammar to use INSERT INTO
> INSERT INTO table_name (column1, column2, column3, ...)
> VALUES (value1, value2, value3, ...);
would you try this one
let query2 = "INSERT INTO address (id,first_line) VALUES ('userId', 'first_line')"
connection.query(query2, (error, results)