0
I would like to know how to best insert an array into a database table. I could use a foreach but I would like something performative because I will work with large number of data.
foreach (var item in registros)
{
string CPF = String.Empty;
string nome = String.Empty;
string apto = String.Empty;
CPF = item.Split('|')[0];
nome = item.Split('|')[1];
apto = item.Split('|')[2];
SqlCommand cmd = new SqlCommand("INSERT INTO DATABASE.DBO.TABLE (CPF, NOME, APTO) VALUES (" + CPF + "," + nome + "," + apto + ")");
}
Depends. How is the database? How should the data be recorded? But I can already tell you that there is no magical command that makes operations huge and things fast.
– Maniero
It will be a table with three simple columns (CPF, NAME, STATUS). I would like the most performative form, I believe it is not the foreach.
– Jean Gustavo Prates
Only with this information can it be very difficult to help you. But I can already tell you that if you are not doing it as fast as possible. That is, the difference if you use a
for
simple will be minimal (I think until it will be worse). Reinforcement that there is no magic solution. If you showed why you need more performance, the overall context, maybe you could suggest something different, but just with this information, I can only say it’s this or thefor
simple, test both and see which is faster. Probably the gain will not be worth the effort.– Maniero
http://answall.com/a/53857/101 looks at how it doesn’t make much difference and how the
foreach
may even be the fastest.– Maniero
I had a similar problem. I needed to save 100,000 records in my BD. Using the form you demonstrated, it was taking about 5 minutes. So instead of saving directly, I used foreach to save the data to a list, and I used Bulkinsert to enter the data. The task changed from 5 minutes to about 15 seconds. If you need it, let me know and I’ll get back to you later.
– Randrade
@Randrade exactly, if he provides more information of the whole process can to find other solutions, only with this stretch can not help much. Loop will be needed to mount the data but it need not be used to write the data.
– Maniero
@Jeangustavoprates, very important: do not concatenate the query values in this way, you are vulnerable to SQL Injection! Use parametrized queries.
– Dherik