'What is the best way to insert an array of variable length of data into a sql database?
So I have a form of variable size and users can add any amount of fields they like.
an example of form values is like this:
{variableSizedArray: [
{name: car1Name, age: car1Age},
{name: car2Name, age: car2Age},
{name: car3Name, age: car3Age},
...
]}
How would I go about inserting each value into my SQL database?
Things I tried:
- Executing a SQL statement for each value:
variableSizedArray.forEach((item) => {
db.exec("INSERT INTO cars (name, age) VALUES (?, ?)", [item.name, item.age]);
})
But this will cause many calls to the database which I believe is bad practice?.
- Creating a custom string:
variableSizedArray.forEach((item) => {
insertString += `(${item.name}, ${item.age}),`;
}
db.exec(`INSERT INTO cards (name, age) VALUES ${insertString}`);
this is the solution I am using right now but it's getting quite complicated since I have much more variables in my project and I need to create a different "custom string" builder for every new "operation" I make.
Are those the only 2 options and is my understanding of their drawbacks correct?
Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
