Insert into mysql database, nodejs separates value - mysql

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

Related

Records not inserting - mySql Node

The Task
I am trying read all the records from one table, and insert them into another table. I will re-use these functions later on in the app.
The Problem
The data doesn't appear to be being passed correctly. I am not getting any errors, yet the records are not inserted.
I debugged the data variable, and all the records are consoled correctly. For some reason, I am losing them when I call my insertData function.
Note: My table name is results, which may be a little confusing. I may change that in the future.
Entire Source Code
var mysql = require('mysql');
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "marketplace"
});
connection.connect(function (err) {
if (err) throw err;
console.log("Connected!");
})
const getData = function (tblName) {
var data = {};
switch (tblName) {
case "results":
sql = "SELECT * FROM results";
break;
case "items":
sql = "SELECT * FROM items";
break;
default:
sql = "SELECT * FROM results";
break;
}
return new Promise(resolve => {
connection.query(sql, function (err, results) {
if (err) {
console.log(err);
} else {
data.numResults = results.length;
data.data = results;
resolve(data);
}
})
})
}
const insertData = function (tbl, entity) {
return new Promise(resolve => {
var sql = `INSERT INTO ${tbl} (title,price,location,miles,imgUrl,itemURL) VALUES ?`;
var insertedIds = [];
for (var i = 0; i < entity.length; i++) {
connection.query(sql, entity[i], function (err, res) {
if (err) throw err;
insertedIds.push(res.insertId);
});
}
resolve(insertedIds);
})
}
const init = async function () {
var data = await getData("items");
console.log(data); // Works. Display all data
var insertSuccess = await insertData("results", data);
}
init();
Data Structure
{
id: 251,
title: '2008 Jeep Wrangler Unlimited Sahara Sport Utility 4D',
price: '$10,500',
location: 'Lake Sarasota, Florida',
miles: '123K miles',
itemURL: '/marketplace/item/174406817245706/',
imgUrl: 'https://scontent-mia3-1.xx.fbcdn.net/v/t1.0-0/c43.0.260.260a/p261x260/98434536_3577078698974198_8432375958719168512_n.jpg?_nc_cat=111&_nc_sid=843cd7&_nc_oc=AQlLn3CVPZmD4dKSsfXd-rV0WxXBo98zneuGAEgz2JP2yWrkt5rxI-fa1ShTtMGYbrw&_nc_ht=scontent-mia3-1.xx&oh=89e552882baeb14c642a1cd28b8ba683&oe=5EEA3991',
seen: 0,
created_date: 2020-05-20T20:45:24.000Z
}
Schema
DROP TABLE IF EXISTS `results`;
CREATE TABLE IF NOT EXISTS `results` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`price` varchar(255) DEFAULT NULL,
`location` varchar(255) DEFAULT NULL,
`miles` varchar(22) DEFAULT 'unavailable',
`itemURL` text,
`imgUrl` text,
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=612 DEFAULT CHARSET=latin1;
COMMIT;
Output
When I try to console.log the insertSuccess variable, which should show me a list of inserted id's:
.
.
.
console.log(insertSuccess);

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.

Mysql Error: trying to find columns in database

Im trying to insert user data into my mysql database but Im getting this error " sql: 'SELECT * FROM users WHERE undefined = ?' "
Here is my code :
find: function(user = null, callback) {
//if the user variable is defined
if(user) {
var field = Number.isInteger(user) ? 'id' : 'email';
}
// prepare the sql query
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result){
if(err) throw err;
if(result.length){
callback(result[0]);
} else {
callback(null);
}
});
},

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)

Ignore update data if exist in mysql by node js

I'm going to check id of my data if exist in mysql update it and if not create it, but in select result it dosen't work and go to esle section and create action most of the times and got Duplicate entry error. at the end I run this file by infinite loop.
I should tell this when I have a lot data in redis this problem will happen.
I'll be glad if help me, thanks :)
Here is my code :
var
mysql = require('mysql'),
redis = require('redis'),
infiniteLoop = require('infinite-loop'),
client = redis.createClient(),
lop = new infiniteLoop,
config = require( __dirname + '/app/Config').config,
con = function() {
return mysql.createConnection({
host : config.db_host,
user : config.db_user,
password : config.db_pass,
database : config.db_name
});
},
insertDB = function( data ) {
var connection = con();
connection.connect( function( err ) {
connection.query( 'SELECT * FROM real_user WHERE id =' + data.id, function( err, res ) {
if ( err ) {
data = JSON.stringify(data);
client.lpush('aipi', data, function(err,reply) {
if ( err ) throw err;
});
}
console.log( "out", data.id, res.length, res );
if ( typeof res != 'undefined' && res.length > 0 ) {
console.log( "update", data.id );
connection.query( 'UPDATE real_user SET ? WHERE id =' + res[0].id, { request_count: data.request_count, updated_at: data.created_at },
function( err, res ) {
if ( err ) throw err;
});
} else {
console.log( "create", data.id );
connection.query( 'INSERT INTO real_user SET ?', data, function( err, res ) {
if ( err ) throw err;
});
}
connection.end();
});
});
},
run = function() {
var data;
client.brpop('aipi', 0, function(err, reply) {
if ( reply[1] ) {
data = JSON.parse(reply[1]);
insertDB(data);
}
});
};
lop.add(run, []).run();
Fixed it by :
ON DUPLICATE KEY UPDATE
connection.connect( function( err ) {
connection.query( "INSERT INTO real_user SET ? ON DUPLICATE KEY UPDATE updated_at = '" + data.created_at
+ "', request_count = '" + data.request_count + "'",
data, function( err, res ) {
connection.end();
});
});