0

I am currently having a confusion with:

var post = {ip: host, status: info};
var sql = con.query('INSERT OR IGNORE INTO ipaddress SET ?', post, 
function(err, result){});

I have already set the IP address to primary key.

Nae
  • 14,209
  • 7
  • 52
  • 79

1 Answers1

1

Sequelize

Since you're using node.js, how about using Sequelize?

Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.

It doesn't matter if you don't know SQL well because you can use its built-in functions. For example, if you want to perform an upsert:

ipaddress.upsert({
    ip: host,
    status: info,
});

Pure MySQL

If you still want to use MySQL, use ON DUPLICATE KEY UPDATE to perform an upsert.

var sql = `INSERT INTO post (ip, status) VALUES (${host}, ${info}) ON DUPLICATE KEY UPDATE ip=${host}, status=${info}`;

But you need to take care some potential issues like SQL injection.

NoobTW
  • 2,466
  • 2
  • 24
  • 42