How best to insert an array into the database

0

I would like to know how to insert an array into a table in the database. I could use a foreach but I would like something performatic because I will work with a 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 + ")");
        }
    
asked by anonymous 07.04.2015 / 22:54

2 answers

1

@JeanGustavoPrates, you can perform the insert only after mounting all INSERTs with SqlBulkCopy or as follows:

string stmt = "INSERT INTO DATABASE.DBO.TABLE (CPF, NOME, APTO) VALUES (@cpf, @nome, @apto)";

SqlCommand cmd = new SqlCommand(stmt, _connection);

cmd.Parameters.Add("@cpf", SqlDbType.VarChar, 100);
cmd.Parameters.Add("@nome", SqlDbType.VarChar, 100);
cmd.Parameters.Add("@apto", SqlDbType.VarChar, 100);

for (int i = 0; i < registros.count i++)
{
    var item = registros[i];
    string CPF = item.Split('|')[0];
    string nome = item.Split('|')[1];
    string apto = item.Split('|')[2];
    cmd.Parameters["@cpf"].Value = CPF;
    cmd.Parameters["@nome"].Value = nome;
    cmd.Parameters["@apto"].Value = apto;

    cmd.ExecuteNonQuery();
}

But anyway, I believe that for to retrieve the CPF, name and apt information you will not be able to escape.

Very important : Do not concatenate the query values this way, you're vulnerable to SQL Injection! Use parametrized queries , as I demonstrated above.

Adapted from: link

    
07.04.2015 / 23:59
2

What you are trying to do is a bulk insert, that is, an insert with a large number of lines at one time. At the start, the best way to do this would be BULK INSERT , but you can also go by the simplest method and do a INSERT statement. This statement will be built into for and executed once only after it. Picking up your code:

string CPF = String.Empty;
string nome = String.Empty;
string apto = String.Empty;
string valuesString = String.Empty;
for(int i = 0; i < registros.count; i++) { 
    var item = registros[i];
    CPF = item.Split('|')[0];
    nome = item.Split('|')[1];
    apto = item.Split('|')[2];
    values += "(" + CPF + "," + nome + "," + apto + ")";
    if (i < registros.count-1) 
       values += ",";
}
if (!String.IsNullOrEmpty(valuesString)) {
   SqlCommand cmd = new SqlCommand("INSERT INTO DATABASE.DBO.TABLE (CPF, NOME, APTO) VALUES " + valuesString;
    ...
}
    
07.04.2015 / 23:50