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]
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");
});
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 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.
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: