I've been trying to make this script work with value binds, but seems it doesn't work with the mainTable variable.
var mainTable = "tasks";
var con = mysql.createConnection({
host: "host",
user: "user",
password: "password",
database: "database"
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
var values = {
id: "id",
url: "url",
assignee: "akjdh",
status: "ahsbdu",
type: "apsokdn",
description: "asd",
department: "department"
};
var query = con.query("INSERT INTO ? SET ? ON DUPLICATE KEY UPDATE ?", [
mainTable,
values,
values
], function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
I get the following 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 ''tasks' SET id = 'id', url = 'url', assignee = 'akjdh', status = 'ahsbdu' at line 1
I don't understand why its failing with if I make the table value into a bind.
Mysql identifiers have to be escaped using a backtick ` and not using '.
? is used to escape value with '
?? is used to escape identifiers with `
As of that it hast to be:
INSERT INTO ?? SET ? ON DUPLICATE KEY UPDATE ?
mysql: Escaping query identifiers
Alternatively, you can use ?? characters as placeholders for identifiers you would like to have escaped like this:
Related
I am currently working on a html form that allows the user to input their title, firstname, surname, mobile and email. Currently this data is being pushed into an in-memory database called userDatabase[].
I want to be able to insert the data into my local mysql database instead. I can connect to my database using this code with no issues.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "user",
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
In the below code you can see that the data is getting pushed into the in-memory database.
if (currentMethod === "POST") {
// read the body of the POST request
request.on("data", function(chunk) {
requestBody += chunk.toString();
});
// determine the POST request Content-type (and log to console)
// Either: (i) application/x-www-form-urlencoded or (ii) application/json
const { headers } = request;
let ctype = headers["content-type"];
console.log("RECEIVED Content-Type: " + ctype + "\n");
// finished reading the body of the request
request.on("end", function() {
var userData = "";
// saving the user from the body to the database
if (ctype.match(new RegExp('^application/x-www-form-urlencoded'))) {
userData = querystring.parse(requestBody);
} else {
userData = JSON.parse(requestBody);
}
//**************** */
userDatabase.push(userData)
I have tried to INSERT the data into my table called "personal" like this: But I am getting an error Error: ER_PARSE_ERROR: 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 'title = 'ms', firstname = 'Tina', surname = 'poole', mobile = '+3...' at line 1
con.query("INSERT INTO personal (title , firstname, surname, mobile , email ) VALUES ?", [userData], function(err, result) {
if (err) throw err;
console.log("1 record inserted");
});
You're conflating two distinct syntax patterns for MySQL's INSERT. In these types of situations you should be referring to the relevant documentation.
When specifying key='value' pairs, the syntax for an INSERT would conform to the following format:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
SET assignment_list
[ON DUPLICATE KEY UPDATE assignment_list]
This format is clearly delineated from the traditional INSERT INTO tbl_name (fieldnames) VALUES (values) as it doesn't require either the field names nor the VALUES keyword, as you've included in your query syntax above. Instead, you'd include the SET <assignment_list> sequence, which operates similarly in syntax to a traditional UPDATE query.
Instead, your code would look similar to the following:
con.query("INSERT INTO personal SET ?", [userData], function(err, result) {
if (err) throw err;
console.log("1 record inserted");
});
Trying to run a query to update a database, and for some reason, MySQL returns:
Error Code: 1064. 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 '?' at line 1
Tried the line just in SQL to see what happened
INSERT INTO eu_profile (id, profileName) VALUES ?
It also fails with the same message in the code:
import * as mysql2 from 'mysql2';
import * from 'mysql2/promise'
/** Lets open the database for mysql2 */
const mysql2connection = mysql2.createConnection({
"host": "localhost",
"port": 3306,
"user": "node",
"password": "NotTellingYou",
"database": "stats"
});
mysql2connection.connect(function(error){
if(!!error){
console.log(error);
}else{
console.log('Connected!:)');
}
});
let dbTables: string="";
let sqlInsert: string="";
dbTables = "id, profileName";
sqlInsert = "INSERT INTO eu_profile ("+dbTables+") VALUES ?"
const profileLoad = await mysql2connection.query(sqlInsert, [profileData], function(err) {
if (err) throw err{
mysql2connection.end();
}else
}).then(console.log("We are done here"));
Version:
If you have two columns you need tiw values
INSERT INTO eu_profile (id, profileName) VALUES (?,?)
Also [profileData] needs 2 values like [req.body.topic, req.body.note]
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 (?) ';
}
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 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.