MySql auto-increment not working while inserting multiple rows - mysql

I am inserting multiple rows in the MySql database table the first row is getting inserted but for remaining it is showing the error:
[Error: ER_DUP_ENTRY: Duplicate entry '2' for key 'PRIMARY']
code: 'ER_DUP_ENTRY',
errno: 1062,
sqlState: '23000',
index: 1,
This is the structure of id field:
If I insert a single row the auto-increment works file.
I am not able to rectify the problem. Please help. Thanks.
EDIT
I am using node-rom2 and the code is
modelObj.create(arrayOfObjects, function (err, result) {
if (err) {
console.log("The error is :", err);
}
else {
response.status = 'success';
response.data = result;
}
next(response);
});
The SQL query is generated dynamically.

Now I got the solution, the mistake I was doing is I was generating the data using a for loop like this:
var data = { name:'john', age:24, email:'abc#abcd.com'};
var arrayOfObjects= [];
for (var i = 0; i < 4; i++){
arrayOfObjects.push(data);
}
modelObj.create(arrayOfObjects, function (err, result) {
if (err) {
console.log("The error is :", err);
}
else {
response.status = 'success';
response.data = result;
}
next(response);
});
So each and every record is same in this condition. However other than id none column having the property primary-key. I think it can be the behavior of the database or the node-orm2 can also be the reason, so it is not accepting the exact same values.
In actual, all the record won't be same. If you have some other point please let me know your thoughts. Thanks.

Related

SQL query results in UnhandledPromiseRejectionWarning: ReferenceError: response is not defined

I am trying to display specific data from a table in mysql using this code. I am in between using a for loop but it says that res or response is not defined. What do I need to edit or change in my code below?
function lowInventory() {
console.log("View all product that are low in inventory...\n");
for (var i = 0; i < response.length; i++) {
connection.query("SELECT stock_quantity (*) FROM products WHERE stock_quantity < 5", function (err, res) {
if (err) throw err;
//log all results of the SELECT statement
console.table(Response);
connection.end();
});
}
}
I need for it to display results of quantity that is less than 5 in node.js from my table.
change console.table(Response) to console.log(Response)

Catching exception errors when logging in via NodeJS + MySQL

Recently I've been trying to learn NodeJS to set up a log in process, so I decided to write all the errors and make exceptions for them. My question is how can I make sure each if is responsible for each error code. I haven't worked with try and catch before so this is a new territory for me.
Also is it better to use multiple try-catch or should I consider using 1 block where I can use a switch for example (used else if here as a quick example).
Table with Status errors
0 - no connection with database.
1 - connection ok but we dont have any privileges for access to the
database or something like that.
2 - all ok.
3 - ok, but no data found in query results.
4 - error getting results of query.
5 - other.
module.exports = (username,password,connection ) => {
var data ={
"Status" : null,
"Data" : {} //JSON results inside of Data Json
}
try{
connection.query("SELECT id FROM players", function (error, results, fields) {
if (error){
data.Status = 0;
data.Data= "No connection can be established with the database";
return data
}
else if(error){
data.Status = 1;
data.Data= results + "Connection OK but no priviliges";
return data
}
else if(error){
data.Status = 2;
data.Data=results + "connection running";
return data
}
else if(error){
data.Status = 3;
data.Data=results + "No data found in query results";
return data
}
else if(error){
data.Status = 4;
data.Data=results;
return data
}
else if(error){
data.Status = 5;
data.Data=results;
return data
}
});
}
catch(e){
console.log(e);
data.Status= 2;
data.Data=null;
return data;
}
};
Welcome to async programming, your try/catch block won't do anything for any I/O process, all errors are handled by error object in the callback function. (unless you use the last async/await ES6 pattern)
connection.query("SELECT id FROM players", function (error, results, fields) {
if (!error) { // no error, return results
data.status = 2;
data.Data = results;
return data;
}
// for all error code, please check mysql library document
// https://www.npmjs.com/package/mysql#error-handling
if (error.code === 'ER_ACCESS_DENIED_ERROR') {
data.Status = 1;
data.Data=results;
return data
}
// handle any other error codes
// if ....
});
Edit: please note that, your exported function in module.exports won't return anything because you are calling database query which is an async I/O process and requires another callback function to get the data returned by database
This will never work as expected :
if (error){
console.log("I'm the error");
return;
} else if(error){
console.log("I will never be display on error because of return in the first if");
}
Should be :
if (!error){
// No error
} else if(error === 'something'){
// Error something
} else if ....
// Other type of error
} else {
// Unknown error
}
You can use a switch instead in a more elegant way :
const data = { Status: 1, Data: results }
if(error) {
switch(error.code) {
case 'ER_ACCESS_DENIED_ERROR' :
data.Satus = 2;
return data;
...
}
}
return data;

NodeJS - Mysql Error while insert data to database

I got a function like getItemPrice in nodeJS. But while trying to inserting datas there is a error occuring. Can't write any dynamic value inside VALUES(item.Id, value.lowest_price).
I've tried lots of things bot none of work.
con.query('SELECT game_item.id as itemId, steam_app_game.app_id as gameId, game_item.name, steam_app_game.id FROM steam_app_game LEFT JOIN game_item ON steam_app_game.id = game_item.app_game_id', function(err, rows, fields) {
var counter = 1;
rows.forEach(function (item,index) {
setTimeout(function(){
market.getItemPrice(item.gameId, item.name).then(function (value, err) {
if(err) throw err;
var lowest = value.lowest_price
con.query('INSERT INTO game_item_spec(game_item_id,price) VALUES (item.itemId,value.lowest_price )')
counter ++;
});
}, index * 5000);
});
});
Here is the error.
ER_BAD_FIELD_ERROR: Unknown column 'value.lowest_price' in 'field list'
at Query.Sequence._packetToError (F:\Xamp\htdocs\steam-trade-bot\node_modules\mysql\lib\protocol\sequences\Sequence.js:47
:14)
I solved this using parameter statements in nodeJs. Single insert into doesn’t work for if the data has special chars
A query must be a string, so to inject some variables inside you can use ES6 syntax with template string.
Here the working code:
con.query('SELECT game_item.id as itemId, steam_app_game.app_id as gameId, game_item.name, steam_app_game.id FROM steam_app_game LEFT JOIN game_item ON steam_app_game.id = game_item.app_game_id', function(err, rows, fields) {
var counter = 1;
rows.forEach(function (item,index) {
setTimeout(function(){
market.getItemPrice(item.gameId, item.name).then(function (value, err) {
if(err) throw err;
var lowest = value.lowest_price
con.query(`INSERT INTO game_item_spec(game_item_id,price) VALUES (${item.itemId}, ${value.lowest_price} )`)
counter ++;
});
}, index * 5000);
});
});
I recommend that you use node async https://caolan.github.io/async/, use series together with eachOfSeries

How to push a json object in array in mongodb with loopback?

Here is my efforts :
async.waterfall([
function(nextCall){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
const dbo = db.db("testmdb");
const criteria = {"_id":ObjectId(id)};
console.log("paymentInof[] ::: ",paymentInfo)
let obj = paymentInfo[0];
const query = {
$push:{payment:obj}
};
dbo.collection("Invoice").update(criteria, query);
db.close();
nextCall(null,{code:200});
});
}
],function(err,results){
if(err) return err;
if(results.code === 200)
console.log(chalk.blue(' ::: all done ::: '));
next();
});
Input from api explorer :
{
"payment":[{"transaction_at":"2018-02-12T06:04:35.279Z","paid_amount":350,"patient_id":"1233sssdd33","patient_urn":"214125","invoice_amount":700,"user":"me"}],
"updated_by": "me"
}
Everything working fine but unable to push instead overwriting the existing object in payment array.
While from mongo shell it is working fine.
Please help me , where I am doing wrong ?
Thanks.
I think you need to check mongoose update upsert option.
Update options
There are several option values that can be used with an update
multi - update all records that match the query object, default is false (only the first one found is updated)
upsert - if true and no records match the query, insert update as a new record
raw - driver returns updated document as bson binary Buffer, default:false
Please check the documentation to here.
Use following code,
async.waterfall([
function(nextCall){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
const dbo = db.db("testmdb");
let criteria = {"_id": ObjectId(id)};
let obj = paymentInfo[0];
let query = { $push: { payment: obj } }
dbo.collection("Invoice").update(criteria, query, {upsert:true});
db.close();
nextCall(null,{code:200});
});
}
],function(err,results){
if(err) return err;
if(results.code === 200)
console.log(chalk.blue(' ::: all done ::: '));
next();
});
Also please check the similar type of question to here and here.
Hope this will help you!!

Node.js - mysql: Bad field Error

I parse a big csv and insert row per row into my mysql tables.
After parsing I do a lot of calculation and transforming and save it to a new Object
obj.push({
"ID": value.id,
"col1": value.calc1,
... });
After the Object is complete I do:
async.forEach(obj, function (Insertobj, callback) {
var query = conn.query('INSERT INTO table SET ?', Insertobj);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}}
After running through the obj I get =>
Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'field list'..
But he inserts the complete Object into my table! I don't have any column called NaN or empty cols. How can I debug it? I try to set the console.log to err.sql, but he print "undefined". Using debug:true in connection didn't help me.
I think you have misunderstood how escaping mysql values works using the node js module. The error is due to you not specifying what column you want to update. In addition to this, the escaped values should be filled in using an array instead of an object. With values being in the order they are escaped in the query. Your code could look as follows:
valuesarray.push([
value.id,
value.calc1
]);
async.forEach(valuesarray, function ( insertarray, callback ) {
var query = conn.query('INSERT INTO table SET ID = ?, col1 =
?', insertarray);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}
});