I have a problem running the following SQL query to my MySQL database with nodeJS and the node-mysql packe which is added with npm.
INSERT INTO locations (locationID,name,latitude,longitude)
SELECT '214777725','Bryans Road,
Maryland','38.628055556','-77.081666667'
FROM dual WHERE NOT EXISTS
(SELECT * FROM locations WHERE locationID = '214777725')
I've tried the following code:
var arrValues = [ -12.9747, -38.4767, 213287181, 'Salvador, Brazil' ];
var arrNames = [ 'latitude', 'longitude', 'locationID', 'name' ];
var locationID = "214777725";
if(imageData["locationID"] != null) {
var query = "INSERT INTO locations ? ";
query = query + " SELECT (?)";
query = query + " FROM dual WHERE NOT EXISTS";
query = query + " (SELECT * FROM locations WHERE locationID = ?)";
console.log(query);
connection.query(query, [arrNames,arrValues,locationID], function(err,res)
{
if(err)
{
console.log(err);
}
else
{
console.log("Insert-Success: " +id);
}
});
}
Running this the console writes following error:
{
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0
}
I hope somebody can help.
It looks like you need to use the .toString(); function on your arrays.
connection.query(query, [arrNames.toString(),arrValues.toString(),locationID], function(err,res)
{ ...
Related
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.
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);
}
});
},
I'm trying to get a query to work in node.js but I can't get it to work. I've tested it in MySQL workbench and in phpmyadmin, and the query works in both. Can someone see what the error is?
I've tried adding backticks to the query, didn't work. Tried to use " instead of ` to start the query, didn't work.
app.get('/meetings/add', (req, res) => {
const { meetingsubject, meetingdescription, bulletpoints, bulletpointslength } = req.query;
var bulletPointQuery = " INSERT INTO `bulletpoints` (`idmeeting`, `bulletpointname`) VALUES ";
var allBulletPoints = bulletpoints.split(',');
for(var i = 0; i < bulletpointslength; i++){
if(i === bulletpointslength - 1){
bulletPointQuery = bulletPointQuery + "(LAST_INSERT_ID(), '" + allBulletPoints[i] + "');";
}else {
bulletPointQuery = bulletPointQuery + "(LAST_INSERT_ID(), '" + allBulletPoints[i] + "'),"
}
}
const insertMeeting = "BEGIN; INSERT INTO `meetings` (`meetingsubject`, `meetingdescription`) VALUES ('" + meetingsubject +"', '" + meetingdescription + "');" + bulletPointQuery + "COMMIT;";
connection.query(insertMeeting, (err, results) => {
if(err){
console.log(err);
return res.send(err);
}else{
console.log("yup");
res.send("sucessfully added meeting");
}
});
});
this is the 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 'INSERT INTO meetings (meetingsubject, meetingdescription) VALUES ('yayeet'' at line 1",
sqlState: '42000',
index: 0,
sql: "BEGIN; INSERT INTO meetings (meetingsubject, meetingdescription) VALUES ('yayeet', 'yaeter'); INSERT INTO bulletpoints (idmeeting, bulletpointname) VALUES (LAST_INSERT_ID(), 'yeet (07:30)'),(LAST_INSERT_ID(), 'wwee (07:30)');COMMIT;"
EDIT
The query i'm trying to work with:
BEGIN;
INSERT INTO `meetings` (`meetingsubject`, `meetingdescription`)
VALUES ('yayeet', 'yaeter');
INSERT INTO `bulletpoints` (`idmeeting`, `bulletpointname`)
VALUES (LAST_INSERT_ID(), 'yeet (07:30)'),
(LAST_INSERT_ID(), 'wwee (07:30)');
COMMIT;
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)
I can pass an array to an mysql insert in nodeJS like so..
var data = {userId: 3, name: "sample"}
db.query('insert into my_table SET ?', data, function(err, result){...}
Is there a similar way of passing an array to a select query in the where clause... without specifying all the fields?
var data = {userId: 3, name: "sample"}
db.query('select * from my_table WHERE ?', data, function(err, result){...}
Doesn't seem to work.. nor does using the SET name in place of where...
database.conn.config.defaultQueryFormat = function (query, values) {
if (!values) return query;
var updatedQuery = query.replace("?", function () {
var whereClause = "";
for(var index in values){
whereClause += mysql.escapeId(index) + " = " + db.escape(values[index]) + " and ";
}
whereClause = whereClause.substring(0, whereClause.length - 5);
return whereClause;
});
return updatedQuery;
};
This appears to work.. e.g.
var val = db.query('select * from my_table where ?', data, function(err, result) {
}