1

This 2d array can be of any length so if for example the array is

var my_2D_Array = 
[['jack',22,'student'],
['Bob',45,'doctor'],
['bucky',30,'unelployed']]

// currently I am using this but it isn't working properly 

for(i=0;i<my_2D_Array.length;i++){
  clientChart.run(`INSERT INTO HP2255 VALUES (?, ?, ?)`,my_2D_Array[i],(err)=>{
  console.log('err' + err)
})

Is it possible to insert an array like this into the database with out using a for loop

I am really new to programming in general and if there is anything that I am missing than please help me out

3
  • You're passing an array to the query not 3 individual values and you aren't specifying which columns the VALUES reference, should be INSERT INTO HP2255 (name, age, job) VALUES (?,?,?);. Which sqlite library are you using? Commented Nov 20, 2021 at 11:42
  • sqlite3 in electron Commented Nov 20, 2021 at 11:52
  • You'll need the for loop, there is a clear example in the Usage section on the repo. I might recommend looking at better-sqlite3 though. Commented Nov 20, 2021 at 12:08

1 Answer 1

2

Without knowing more about your setup/table definition and based on the Usage presented in the repo I would guess something like the following:

const my_2D_Array = [
  ['jack', 22, 'student'],
  ['Bob', 45, 'doctor'],
  ['bucky', 30, 'unelployed'],
];

// explicitly declare columns (it may work without, but is more fragile and less clear)
const stmt = clientChart.prepare('INSERT INTO HP2255 (name, age, job) VALUES (?, ?, ?)');
for (const row of my_2D_Array) {
  stmt.run(...row); // spread each sub-array to pass the individual elements
}
stmt.finalize();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.