Hi, I want to write data to a table, they are written, but if I try to write again, it creates a duplicate. Actually the question: I just need to output to a separate variable so that they are not created? Here is my code:

var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "steam_bot" }); function RecordUsers() { console.log("Соединение установлено!"); var sql = "UPDATE `users` SET name ='Test' WHERE steamid = '"+steamID+"'"; con.query(sql, function (err, rows, result) { if (err) throw err; console.log("1 record update"); if (rows[0] < 1) { var sql = "INSERT INTO `users`(name, steamid) VALUES ('Testovino','"+steamID+"')"; con.query(sql, function (err, result) { console.log("1 record insert"); }); } }); } 

Google, everywhere Pyha ..

  • not familiar with technologies, but what do you expect in row[0] when you run an update request? it does not return a data set. It may, of course, be the number of affected lines, but I doubt something. - teran
  • It is possible in the structure of the table to make the field 'steamid' unique, then the same records will not be inserted. Well, I also do not understand why there UPDATE /. Maybe instead of SELECT, to check whether there are entries with steamID - Maxim Stepanov
  • those. I can make a SELECT query * FROM users WHERE steamid = '"+ steamID +"'? But it returns flat lines all exactly, but how do I get a handle from them ?. @ MaksimSteanov - Snegan
  • Frankly speaking, I am also not familiar with technologies, but in theory it can be this way: get the variable value of the query 'SELECT COUNT (*) FROM users WHERE steamid =' "+ steamID +" '', this is the number of matches, if it is greater than 0, not add - Maxim Stepanov
  • in mysql there is a construction like insert ... on duplicate key update .. - teran

1 answer 1

Understood, I changed the query to SELECT

 var sql = "SELECT `steamid` FROM `users` WHERE steamid = '"+steamID+"'" 

Then sparsil answer through result. And checked for the presence of lines:

 if (result < 1) { var sql = "INSERT INTO `users`(name, steamid) VALUES ('Testovino','"+steamID+"')"; con.query(sql, function (err, result) { console.log("1 record insert"); }); } 

Then I added the else:

 else { var sql = "UPDATE users SET name='Snegan' WHERE steamid='"+steamID+"'"; con.query(sql, function (err, result) { console.log("1 record update"); }); } 

And duplicate check done! Thank you for not passing by.