Skip to content
Advertisement

is there any way to insert an array values into INT datatype in SQL?

I am trying to insert into a table called Observations, I need to insert 10 rows using for loop, I have an array of 10 values that need to be inserted in a column called sens_value which is an INT type. I have tried the following code but it cant take sensValues[i] as an INT.

I am using noodjs to insert into tables using mariadb database.

Basically I am looking for a way to insert different INT values into my SQL statement using for loop. I tried the following code:

const mariadb = require('mariadb/callback');
const dbConn = mariadb.createConnection({host: 'localhost', user:'tudublin', password: 'tudublinpwd', database: 'IoT'});

var sensValues = [10,20,30,15,18,22,28,33,16,40];

for (var i in sensValues) {

    console.log(sensValues[i]) //10,20,30,15,18,22,28,33,16,40
    
    var sql = "INSERT INTO Observations (sensor_id, sens_value, sens_units, dt_added) VALUES (2, sensValues[i], 'C Deg per Volt', now());";
    dbConn.query(sql, insertCallback)
}

function insertCallback(err, res)   {
    if (err) {new Date().getTime()
      console.log(err.message);
    } else {
        console.log(res); 
        dbConn.end();
    }
}

Advertisement

Answer

The sensValues[i] in the VALUES is treated as a string, not as a value from the array. Pass it on as a parameter:

var sql = "INSERT INTO Observations (sensor_id, sens_value, sens_units, dt_added) VALUES (2, ?, 'C Deg per Volt', now());";
dbConn.query(sql, [sensValues[i]], insertCallback)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement