Node mysql ER_PARSE_ERROR 1064 - mysql

I am inserting a row into table like this but its not working i searched on internet and tried all solutions for no luck for me i don't know what i am doing wrong here
var b = req.body;
mysqlConnection.query(
'INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES ?',
[[
b.nid,
b.name,
b.dob,
b.gender
]],
(error, results) => {
if(!error)
res.status(201).send(result.insertId);
else
res.send(error)
}
);
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 '123, 'Alex', '2020-10-30', 'male' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES 123, 'Alex', '2020-10-30', 'male'"
}

There is a missing parenthesis just after VALUES, try this
mysqlConnection.query(
'INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES (?)',
[[
b.nid,
b.name,
b.dob,
b.gender
]],
(error, results) => {
if(!error)
res.status(201).send(result.insertId);
else
res.send(error)
}
);

[You can see attached image and do something like that. I think you are doing bulk insert.
var b = req.body;
mysqlConnection.query(
INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES ?',
b.map(item => (item.nid, item.name, item.dob, item.gender)),
(error, results) => {
if(!error)
res.status(201).send(result.insertId);
else
res.send(error)
}
]
Attached Image:1
And if you are not doing bulk insert then do something like below:
mysqlConnection.query('INSERT INTO `users` (`nid`, `name`, `dob`, `gender`) VALUES (?,?,?,?)',[b.nid,b.name,b.dob,b.gender],
(error, results) => {
if(!error)
res.status(201).send(result.insertId);
else
res.send(error)
}

Related

You have an error in your SQL syntax; BEGIN LOCK TABLES UNLOCK

I am trying to replicate this raiserle sample code
But I am having this error:
{
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
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 'LOCK TABLES `individual` WRITE INSERT INTO individual (email, last_name, firs...' at line 1",
sql: "BEGIN LOCK TABLES `individual` WRITE INSERT INTO individual (email, last_name, first_name, phone_number, auth_string, suppress_email_sending, is_participant, org_id, suborgs, roles, initiation_date, created_at, modified_at, created_by, modified_by) VALUES ('king23garoo#sample.com', 'Garoo', 'King', NULL, '111111111100000000000000000111111111111111111110000001000', 0, 1, 1, '1', '6', '2022-06-01T10:39', NOW(), NOW(), '1', '1')"
}
This is my code:
db.query(
"BEGIN LOCK TABLES `individual` WRITE INSERT INTO individual
(email, last_name, first_name, phone_number, auth_string,
suppress_email_sending, is_participant, org_id, suborgs,
roles, initiation_date, created_at, modified_at, created_by, modified_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, '?', '?', ?, NOW(), NOW(), ?, ?)",
[
data.email,
data.last_name,
data.first_name,
data.phone_number,
data.auth_string,
data.suppress_email_sending,
data.is_participant,
data.org_id,
data.suborgs,
data.roles,
data.initiation_date,
data.created_by,
data.modified_by,
],
(err) => {
console.log(err)
if (err) return result(err, null)
db.query("SET #last_ind_id = LAST_INSERT_ID()");
"UNLOCK TABLES"
db.query(
"INSERT INTO ind_group
(ind_id, program_id, iteration_id, org_id, suborg_id,
created_at, modified_at, created_by, modified_by)
VALUES (#last_ind_id, ?, ?, ?, ?, NOW(), NOW(), ?, ?) END",
[
data.indGroup.program_id,
data.indGroup.iteration_id,
data.org_id,
data.suborgs,
data.created_by,
data.modified_by,
],
(err, results) => {
console.log(results)
console.log(err)
if (err) return result(err, null)
result(null, results)
});
})
I have a unique constraint on the email, What I am trying to achieve is to put the LAST_INSERT_ID() from the individual table, into the ind_group table. Is this a good approach? or is there another way to get the last inserted id from table1 to be inserted in table2

How to check if record was changed on db after inserting data?

I insert some data from a db.table1 to db.table2 with a cronjob which runs every minutes. But I need to check if any record has changed after data is inserted on table2 because I get some wrong data on this table when data is inserted.
this is crontab function
$data = DB::connection('mysql2')
->table('students')
->where('status', '=', 'Y')
->get();
foreach ($data as $key => $aStudent) {
// Check if student_id duplicated
$existing_data_in = DB::table('student')
->where("student_id", $aStudent->student_id)
->first();
if (! $existing_data_in) {
DB::connection('mysql')->table('student')->insert([
"first_name" =>$aStudent->first_name,
"last_name" =>$aStudent->last_name,
"age" =>$aStudent->age,
"student_id" =>$aStudent->student_id,
"created_at" =>$aStudent->created_at
]);
}
}
Log::info('Success, Data Updated');
Or maybe should I run cronjob rarely? My problem is when some record on table1 are filed with data and when this record goes to table2 are empty on table2. If I check same student_id on table1 is okay but on table2 are saved empty
i have loged my query on cronjob and this is what i get in case i find an empty filed on table 2. So last name on table 1 in this case is filled with really last name but on table 2 is inserted as empty and this is query (what hapend)
[2022-01-19 14:16:17] local.INFO: select `student_id` `first_name`, `last_name`, `age`, `created_at` from `students` where `student_id` = ? limit 1 [421]
// this comes from query where i check for dublicated lines i think
[2022-01-19 14:16:17] local.INFO: select * from `student` where `student_id` = ? limit 1 [421]
[2022-01-19 14:16:17] local.INFO: insert into `student`
(`student_id`, `first_name`, `last_name`, `age`, `created_at`) values
(?, ?, ?, ?, ?)
["421","name","","38","2022-01-19 14:13:35"]
If the tables contain created_at and updated_at columns, you can tell if a record has been updated by comparing the two columns.
->whereRaw('created_at != updated_at')->get();
You could wrap everything in a transaction to make sure it works as it should.
$data = DB::connection('mysql2')
->table('students')
->where('status', '=', 'Y')
->get();
$dataToInsert = $data->map(function ($item) {
return [
'first_name' => $item->first_name,
'last_name' => $item->last_name,
'age' => $item->age,
'student_id' => $item->student_id,
'created_at' => $item->created_at
];
})->all();
$columnsToCheck = ['student_id'];
$columnsToUpdate = [];
$conn = DB::connection('mysql');
$conn->beginTransaction();
try {
$conn->table('student')->upsert($dataToInsert, $columnsToCheck, $columnsToUpdate);
$conn->commit();
Log::info('Success');
} catch (\Exception $e) {
$conn->rollBack();
Log::error($e);
}
I'm using upsert. You can read more about it here.
https://laravel.com/docs/8.x/queries#upserts

Insert into mysql database, nodejs separates value

I want to insert into my table values which I get from my front.
so. I have
const Workers = function (workers) {
this.id = workers.id,
this.workers = workers.workers,
this.room = workers.room,
this.team = workers.team,
this.city = workers.city,
this.hotel_name = workers.hotel_name,
this.address = workers.address
};
Workers.create = (newWorkers, result) => {
sql.query(`INSERT INTO rooms_split (workers, room, hotel_name, address, createdAt, updatedAt) VALUES( ? , ? , ? , ?, DEFAULT, DEFAULT )`,
[newWorkers.workers, newWorkers.room, newWorkers.hotel_name, newWorkers.address], (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created splitted room: ", {
id: res.insertId,
...newWorkers
});
result(null, {
id: res.insertId,
...newWorkers
});
});
};
And there is my controller
exports.create = (req, res) => {
console.log("body " + JSON.stringify(req.body));
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
const workers = new Workers({
workers: req.body.workers,
room: req.body.room,
hotel_name: req.body.hotel_name,
address: req.body.address
});
Workers.create(workers, (err, data) => {
if (err)
res.status(500).send({
message: err.message || "Some error occurred while creating the Alias."
});
else res.send(data);
});
}
Output from
console.log("body " + JSON.stringify(req.body));
is
body {"workers":["John Snow","Juri Boyka"],"room":"45","hotel_name":"Test Hamburg","address":"Hamburg 5, test Strase"}
and it looks fine but when is time to insert it into table I got 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 ''Juri Boyka', `room` = '45', `team` = NULL, `city` = NULL, `hotel_na' at line 1",
sqlState: '42000',
index: 0,
sql: "INSERT INTO rooms_split SET `id` = NULL, `workers` = 'John Snow', 'Juri Boyka', `room` = '45', `team` = NULL, `city` = NULL, `hotel_name` = 'Test Hamburg', `address` = 'Hamburg 5, test Strase'"
}
I kniw what this error means but I have no idea why when I want to make query nodejs(?) separates my value so instead ['something','something2'] I got 'something', 'something2' and he is right that there are not enough columns
Change
[newWorkers.workers, newWorkers.room, newWorkers.hotel_name, newWorkers.address]
to
[newWorkers.workers.join(), newWorkers.room, newWorkers.hotel_name, newWorkers.address]
since the workers data type in MySQL is varchar. Therefore, you'll need to stringify your incoming workers array

unable to insert dynamic rows into table using mysql and nodejs

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.

How to insert values into Mysql.js table in Node express project

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)