How to insert a data table into the database?

Asked

Viewed 1,654 times

0

People already have my datatable filled with the values that came from a file . csv now need to insert into database without using Sqlbulkcopy...how to do ? via c#

This method fills my datatable:

public DataTable RetornaDtPreenchido(string caminho){
    DataTable dt = CriaDataTable();
    using (StreamReader arquivo = new StreamReader(caminho)){
    string linhaArquivo;
    string[] campos;
    DataRow registro;
    bool cabecalhoJaLido = false;

        while (!arquivo.EndOfStream){

            linhaArquivo = arquivo.ReadLine();

        if (!cabecalhoJaLido){
            cabecalhoJaLido = true;
            continue;
        }

            campos = linhaArquivo.Split(new string[] { ";" }, StringSplitOptions.None);

            registro = dt.NewRow();

            try{
                bool resultNumero;
                int numero;

                resultNumero = int.TryParse(campos[4], out numero);
                registro["Numero"] = numero;

                if (!resultNumero){
                    Label1.Visible = true;
                    Label1.Text = "Campo numero não esta vindo como valor inteiro";
                }

                bool resultTipoPessoa;
                int tipoPessoa;

                resultTipoPessoa = int.TryParse(campos[2], out tipoPessoa);
                registro["TipoPessoa"] = tipoPessoa;

                if (!resultTipoPessoa || tipoPessoa > 1){
                    Label2.Visible = true;
                    Label2.Text = "Campo Tipo Pessoa com valor inválido";
                }

                bool resultEstado;
                int estado;

                resultEstado = int.TryParse(campos[7], out estado);
                registro["Estado"] = estado;

                if (!resultEstado || RetornaListaEstado(estado) == false){
                    Label3.Visible = true;
                    Label3.Text = "Campo Codigo Estado não é válido";
                }

                if (campos[0].Length > 70){
                    registro["Nome"] = "";
                    Label4.Visible = true;
                    Label4.Text = "Campo Nome excedendo limite de caracteres";
                }else{
                    registro["Nome"] = campos[0].ToString().Trim();
                }

                if (fgCpfCheck(campos[1]) == false){
                    registro["Documento"] = "";
                    Label5.Visible = true;
                    Label5.Text = "CPF Inválido";
                }else{
                    registro["Documento"] = campos[1].Trim().ToString();
                }

                if (campos[3].Length > 100){
                    registro["Endereco"] = "";
                    Label6.Visible = true;
                    Label6.Text = "Campo Endereco excedendo limite de caracteres";
                }else{
                    registro["Endereco"] = campos[3].Trim().ToString();
                }

                if (campos[5].Length > 20){
                    registro["Complemento"] = "";
                    Label7.Visible = true;
                    Label7.Text = "Campo Complemento excedendo limite de caracteres";
                }else{
                    registro["Complemento"] = campos[5].Trim().ToString();
                }

                if (campos[6].Length > 60){
                    registro["Bairro"] = "";
                    Label8.Visible = true;
                    Label8.Text = "Campo Bairro excedendo limite de caracteres";
                }else{
                    registro["Bairro"] = campos[6].Trim().ToString();
                }

                if (campos[8].Length > 100){
                    registro["Cidade"] = "";
                    Label9.Visible = true;
                    Label9.Text = "Campo Cidade excedendo limite de caracteres";
                }else{
                    registro["Cidade"] = campos[8].Trim().ToString();
                }

                if (campos[9].Length > 10){
                    registro["CEP"] = "";
                    Label10.Visible = true;
                    Label10.Text = "Campo CEP excedendo limite de caracteres";
                }
                {
                    registro["CEP"] = campos[9].Trim().ToString();
                }

                if (Label2.Visible == false && Label3.Visible == false){
                    dt.Rows.Add(registro);
                }else{
                    Label11.Visible = true;
                    Label11.Text = "Operação não realizada!";
                }
            }
            catch (Exception ex){
                throw new Exception(ex.Message);
            }
        }
    }
    return dt;
}
  • Do you have any example code ready to put in your question?

  • ta ai edited the dt I have already accurate certificate plays him on the bench or if the field CPF is repeated have to update instead of inserting understood @Cigano Morrison Mendez ?

  • Right. I get it. You want to check the repetition at the bank level or at the level of your StreamReader?

  • at bank level...if Cpf coming from my Streamreader record already exists in the bank...this record should not be inserted but should update this guy who is in the bank

  • This would be the case for another question within your question, but I believe a query bringing a Dataset that can be converted into a Dictionary would be the way.

1 answer

1

I’m a little rusty about it, but a little double Sqldataadapter with Sqlcommandbuilder can be a hand on the wheel.

Anything of the kind:

using (SqlConnection connection = foo /*assumindo que foo é uma conexão pronta*/)
{
    using (SqlCommand command = bar /*monta um SqlCommand com o SELECT relevante. Vale SELECT * FROM tuaTabela, por exemplo.*/)
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter(command, connection))
        {
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            adapter.fill(dt); // dt vazio aqui, ok?
            /* aqui você preenche a tabela */
            adapter.Update(dt); // Só felicidade agora.
        }
    }
}

The Data Adapters (has others besides for SQL, all children of System.Data.Dbdataadapter) are components that fill a table or dataset based on the return of the database.

It turns out that the table/dataset and the Data Adapter have events that are captured and watched by Command Builder. Then the Builder will generate the commands INSERT, UPDATE and DELETE corresponding to what you’ve been doing on the table automatically.

When you call the method Update of Data Adapter, it takes commands with Builder and executes them in the database. In your case virtually all commands will be INSERT. The cool thing is that if the table was already filled in, every change you made to Datatable could be easily applied also in the database in this way :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.