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, "월요일"`);
Related
I'm trying to parse a URL in an Express backend but when I go to a url like http://localhost:5000/reset-password?token=Wp+JCrZGAHEbDgyC4BExpWkX17Y0eurUZMu0zmu7J/5S3ChuRXoi3qdBFtdt6UlOJvMlsR4dOlMwlUS/u9UbWQ==&email=test#test.com I get error: ER_PARSE_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 '(email,token) VALUES ('test#test.com', 'Wp JCrZGAHEbDgyC4BExpWkX' at line 1
My code:
router.get('/reset-password', function(req, res, next) {
const token = req.query.token;
const email = req.query.email;
connection.query('SELECT * FROM resettoken(email,token) VALUES (?, ?)', [email, token], function(err, result) {
if (err) throw err;
Where have I gone wrong? Why req.query.token takes only part of token 'Wp JCrZGAHEbDgyC4BExpWkX' instead of 'Wp+JCrZGAHEbDgyC4BExpWkX17Y0eurUZMu0zmu7J/5S3ChuRXoi3qdBFtdt6UlOJvMlsR4dOlMwlUS/u9UbWQ=='
Problem was with connection.query, right one is:
connection.query('SELECT * FROM resettoken WHERE email = ? AND token = ?', [email, token], functi...
I am trying to get my nodejs to insert into my mysql database, but I'm getting a parse error. Please help if anyone can see an error:
var con = mysql.createConnection({
host: "XXX",
user: "XXX",
password: "XXX",
database: "XXX"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql;
if(req.body.role == "tutor")
{
sql = 'INSERT INTO Tutor (sesh_save) VALUES ? ';
}
else if(req.body.role == "student")
{
sql = 'INSERT INTO Students (sesh_save) VALUES ?';
}
var yoy = 'yoy';
con.query(sql, yoy, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
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 ''yoy'' at line 1
Thanks again...Sorry if this is a dumb question, but mysql insertion is always the hardest thing for me to debug.
Second argument in con.query need to be an array in your case:
Add array brackets [ ] around yoy variable
con.query(sql, [yoy], function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
Alternatively add brackets ( ) in values if you don't want to use array brackets,
Replace your sql lines with following-
if (req.body.role == "tutor") {
sql = 'INSERT INTO Tutor (sesh_save) VALUES (?) ';
}
else if (req.body.role == "student") {
sql = 'INSERT INTO Students (sesh_save) VALUES (?) ';
}
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 have a number of values in a JSON file set out as follows:
[{"scraped_at": 1533384162.2934802, "server_id": "461235834994032661", "invite_code": "5uWt6B", "server_name": "Magic Pokemon", "members": ["115385224119975941", "133557837598031872"]}
As can be seen the last value is another array. I've been trying to use the following code to insert into the mysql database using node.js:
const fs = require('fs');
var obj;
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "list"
});
fs.readFile('list.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
for(var i = 0; i < obj.length; i++) {
const s_at = obj[i].scraped_at;
const s_id = obj[i].server_id;
const s_inv = obj[i].invite_code;
const s_sn = obj[i].server_name;
const mbs = obj[i].members;
const sql = 'INSERT INTO members (scraped_at, server_id, invite_code, server_name, servermbs) VALUES ('+s_at+','+s_id+','+s_inv+','+s_sn+','+mbs+')';
con.query(sql, function (err, result) {
if (err) throw err;
console.log("x record inserted");
});
}
});
});
I'm currently getting the following error thrown:
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 'RP,115385224119975941,133557837598031872,160105994217586689,212681528730189824,2' at line 1
Anyone got any ideas what is up with it and if so any solutions?
Apologies if the code doesn't look too great as I've never been good at formatting on this community site.
Thanks!
I have created a normal registration form with following fields:
name,email,dob,gender,password
i am using express.js and within post route i access it via
req.body.(param)
console.log(req.body) shows all params.
Now i have mysql table with same columns as mentioned before. If i do insert with plain strings (eg: abcs) it works i.e. value is inserted into mysql table. Also the email in form is username in db.
When I try inserting all the fields it shows error :( unknown username field ). username varchar(50) is its definition. in the logs i see password field's input is surrounded with single quotes but as for email it becomes: ('user#mail'.'com'). I also used knex, alternate ways as mentioned in mysql docs and got same error(unknown username) .
Can someone tell me how should i store email in mysql db via nodejs+express
db.js
var mysql = require('mysql');
// setup mysql
var dbcon = mysql.createConnection({
host: 'localhost',
database: 'test',
user: 'flip',
password: 'flop'
});
dbcon.connect(function (err) {
if (err) throw err;
console.log("Connected to db");
});
module.exports = dbcon;
routes/index.js:
var dbcon = require('../db');
.
.
router.post('/signup', function (req, res) {
console.log(req.body);
/* knex('users').insert( {
user_id: 1,
password: req.body.su_password,
u_firstname: req.body.su_firstname,
u_lastname: req.body.su_lastname,
u_gender: req.body.su_gender,
u_dob: req.body.su_date,
}).then(function(arg){
console.log(arg);
});
*/
dbcon.connect(function (err) {
var sqlv = {
user_id: 1,
password: req.body.su_password,
u_firstname: req.body.su_firstname,
u_lastname: req.body.su_lastname,
u_gender: req.body.su_gender,
u_dob: req.body.su_date
};
/*var sql = "insert into `users` values (?,??,??,??,??,??,??);";
var sqlv = [1,req.body.su_email, req.body.su_password, req.body.su_firstname, req.body.su_lastname, req.body.su_gender, req.body.su_date];
sql = mysql.format(sql,sqlv);
*/
//var sql ="insert into usertmp (`username`,`password`) values ('"+req.body.su_email+"','"+req.body.su_password+"');";
dbcon.query("insert into users values ? ;", sqlv, function (err, result) {
if (err) {
console.log(err);
throw err;
}
console.log("inserted into users " + result);
});
});
res.redirect('/');
});
console.log(req.body) in routes/index.js:
{ su_firstname: 'user',
su_lastname: 'virus',
su_email: 'user#mail.com',
su_gender: 'm',
su_date: '1999-01-01',
su_password: 'passowrd00' }
Error(for current example):
{ 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_id = 1, password = 'passowrd00', u_firstname = 'user', u_lastname =' at line 1
Error(for insert using actual sql query with single quotes around each value):
Unhandled rejection Error: ER_BAD_FIELD_ERROR: Unknown column 'username'
in 'field list'
I figured it out !
It wasn't nodejs/expresjs mistake it was from the database.
In the database i had used triggers and forgot to use NEW/OLD prefixes.