I have a function that inserts into a database a random number in a column that is the primary key.
I have a problem when the number is already in the database I want to call the process again to change the number and try to insert again but I am a novice with Javascript so here is the code I have come up with so far.
Function that create a random number:
EDIT 2:
function crearNumero()
{
var aNumeros = new Array
(
'1', '2', '3','4','5','6','7','8','9'
);
var cNumero = aNumeros[Math.floor(Math.random()*aNumeros.length)];
return cNumero;
}
Function that inserts in to the database:
function insertarNumero(Callback)
{
var sql='INSERT INTO tabla_numero(numero) VALUES(?)';
var params= [crearNumero()];
client.query(sql,params,function(err,rows)
{
if(err){
arguments.callee(Callback);
} else {
return Callback(params[0]);
}
});
}
So I try to insert the number with this:
insertarNumero(function(args)
{
console.log('el numero ingresado fue '+args);
console.log('the number inserted was '+args);
});
This code is ok but when the number exists already I dont know how to repeat de process.
Can anyone give me an indication as to how I can go about solving this issue?
You want to actually pass a callback function to the
insertarNumerofunction, like so:This will cause the
insertarNumerofunction to re-call this function, should it fail. Be advised that you should probably also check the error code so that you don’t attempt to insert multiple times, if there was a connection error, for example.Edit: Seeing as you’re still having difficulty resolving your issue, here are two alternatives which might help you:
And if you really don’t want the
insert()function…