I am trying to dynamically build a mysql statement but I keep getting incorrect syntax.
const tableName = user_data;
const insertSet = {'id': 1, 'dependents': ['sarah', 'john']}
conn.query('insert into ?? set ?', [tableName, insertSet], (err,rows) => {
if (err) reject(err);
resolve(rows);
}
When I try this I get the following error:
You have an error in your SQL syntax
In the error message, I saw that the sql it tried to run is
insert into user_data set id = 1, dependents='sarah','john';
It took away the array from dependents and this caused the syntax error.
It should be
insert into user_data set id = 1, dependents=[ 'sarah','john' ];
Related
Referring to this thread How do I do a bulk insert in mySQL using node.js I have written the below code
const values = [
['e33b3c34923500e6', 'The Office', '330248b39a55d82a', '690db8528741c098'],
['e33b3c34923500e7', 'Prison Break', '330248b39a55d82a', '690db8528741c098']
]
let sql = `INSERT INTO Result (resultId, result, submissionId, questionId) VALUES ?`
connection.query(sql, [values], (err, res) => {console.log(err)
console.log(res)
})
Normal single inserts work with the given values but whenever trying to bulk insert like above I get the following error:
return await usedQueryRunner.query(query, parameters); // await is needed here because we are using finally TypeError: usedQueryRunner.query is not a function
I can't insert json value into table.
const mysql = require('mysql');
const user = {};
const connection = mysql.createConnection({
host:'localhost',
user:'root',`enter code here`
password:'homi98',
database:'homi',
port:'3306',
});
user.path = "C:\\nodejsWorkspace\\Mysql";
user.date = "20190805";
user.weather = "sunny";
user.temp = 31;
user.day = "월요일";
console.log(user);
connection.connect();
connection.query('insert into homi01 (path,date,weather,temp,day) values (.$user[\'path\'].,\'20190805\',\'sunny\',31,\'월요일\'); '
,(error, results, fields) => {
if(error) throw error;
console.log(results);
});
connection.end();
Error: ER_PARSE_ERROR: 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 '.$user['path'].,'20190805','sunny',31,'월요일')' at
line 1
at Query.Sequence._packetToError
The query is not syntactically incorrect due to the way you are extracting values from your object. Use Template Strings to make this kind of concatenation simpler.
connection.query(`insert into homi01 (path, date, weather, temp, day) values ( "${user.path}", 20190805, "sunny", 31, "월요일"`
,(error, results, fields) => {
if(error) throw error;
console.log(results);
});
Edit:
If you have problems using Template Strings, here is how your query will be logged:
var user = {path: 'c:\\temp'}
console.log(`insert into homi01 (path, date, weather, temp, day) values ( "${user.path}", 20190805, "sunny", 31, "월요일"`);
Getting a syntax error here but can't figure out why?
Have tried using con.escape as well. Gives the same error.
var sql1 = "INSERT INTO Captcha (Captcha_Image) VALUES ('"+imgBase64+"') WHERE Session_ID = '"+x+"'";
await con.query(sql1, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
//Both imgBase64 and x are varchar values and are being stored in correctly
how to solve this error:
Error: ER_PARSE_ERROR: 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 'WHERE Session_ID =
'93e23e3f7d17b1c50107aa6277cb303985e38e1a5faa0a505064806c291a' at line
1
Insert statements in SQL don't have a WHERE clause, so the following should work without error:
var mysql = require('mysql');
var con = mysql.createConnection({ ... });
var sql1 = "INSERT INTO Captcha (Captcha_Image) VALUES (?)";
con.query({
sql: sql1,
timeout: 40000,
},
[imgBase64],
function (error, results, fields) {
}
);
However, a WHERE clause might make sense if you were doing an INSERT INTO ... SELECT, with a select query serving as the source of data to be inserted. Something like this:
INSERT INTO Captcha (Captcha_Image)
SELECT Captcha_Image
FROM some_other_table
WHERE Session_ID = '93e23e3f7d17b1c50107aa6277cb303985e38e1a5faa0a505064806c291a';
If you instead want to change the Captcha image for records which already exist in the table, based on the session id, then you should be doing an update, not an insert:
con.query('UPDATE Captcha SET Captcha_Image = ? WHERE Session_ID = ?',
[imgBase64, x],
function (error, results, fields) {
if (error) throw error;
console.log('changed ' + results.changedRows + ' rows');
}
);
I am trying to insert multiple records into MYSQL from Node.js with a WHERE clause but I keep getting a syntax error.
The statement works fine until I try to add a conditional statement to it. Then I get this error: ER_PARSE_ERROR: You have an error in your SQL syntax near VALUES ? WHERE ...
var Data = data; // this is a nested array already as received from client side like [[..],[..],[..]]
var ID = 123;
var sql = "INSERT INTO table1 (Col1,Col2,Col3,Col4,Col5) VALUES ? WHERE"+ID+" NOT IN (SELECT somecol FROM table2 WHERE somecol= "+ID+")"
connection.query(sql, [Data], function (error, result) {
if (error) {
throw error;
res.json({ Message: "Oops something went wrong :("});
}
res.json({ Message: "Your data was added!"});
});
The connection is set up to allow multiple statements already:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'thedb',
port: 12345,
charset: "utf8mb4",
multipleStatements: true
});
The query works in this form without the WHERE clause:
var Data = data; // this is a nested array already as received from client side like [[..],[..],[..]]
var ID = 123;
var sql = "INSERT INTO table1 (Col1,Col2,Col3,Col4,Col5) VALUES ?"
connection.query(sql, [Data], function (error, result) {
if (error) {
throw error;
res.json({ Message: "Oops something went wrong :("});
}
res.json({ Message: "Your data was added!"});
});
How do I get the query work with the WHERE clause?
Insert command will not work with Where clause because you are inserting a new row. In naive terms, a Where clause needs some rows to filter out based on the conditions. Based on your use case you can have two possible solutions:
Use Update statements which could be like
Update table set col1=val1 where (condition clause)
If you really want to use Where clause then you can use the Insert command in the following form
Insert into table(col1,col2)
Select (val1, val2) from table2 where (condition clause);
I parse a big csv and insert row per row into my mysql tables.
After parsing I do a lot of calculation and transforming and save it to a new Object
obj.push({
"ID": value.id,
"col1": value.calc1,
... });
After the Object is complete I do:
async.forEach(obj, function (Insertobj, callback) {
var query = conn.query('INSERT INTO table SET ?', Insertobj);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}}
After running through the obj I get =>
Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'field list'..
But he inserts the complete Object into my table! I don't have any column called NaN or empty cols. How can I debug it? I try to set the console.log to err.sql, but he print "undefined". Using debug:true in connection didn't help me.
I think you have misunderstood how escaping mysql values works using the node js module. The error is due to you not specifying what column you want to update. In addition to this, the escaped values should be filled in using an array instead of an object. With values being in the order they are escaped in the query. Your code could look as follows:
valuesarray.push([
value.id,
value.calc1
]);
async.forEach(valuesarray, function ( insertarray, callback ) {
var query = conn.query('INSERT INTO table SET ID = ?, col1 =
?', insertarray);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}
});