How to verify if there is a certain ID in the database?

Asked

Viewed 3,248 times

2

I’m validating before importing a file. csv to the database via C# , I have already done a validation to ensure that the state code is an integer and also need to check if there is the state code that is coming in . csv is actually registered in my database...how can I do that ? here is my method that makes the validations:

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)
            {
                Label3.Visible = true;
                Label3.Text = "Campo Codigo Estado não esta vindo como valor inteiro";
            }

            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";
            }
            else
            {
                registro["CEP"] = campos[9].Trim().ToString();
            }

            if (Label2.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;
}

I am passing this top method for this other method...that it will yes access the bank and import the file. csv

public void ProcessarImportacao(string caminho)
        {
            using (SqlConnection conexao = new SqlConnection(ConfigurationManager.ConnectionStrings["MC1_DB_TREINAMENTOConnectionString"].ConnectionString))
            {
                conexao.Open();

                using (SqlBulkCopy bc = CreateSqlBulkCopy(conexao))
                {
                    bc.WriteToServer(RetornaDtPreenchido(caminho));
                }
            }
        }
  • Give more information. What technology are you using to access the database? Do you want the resultEstado be located? How is your DB structured? Help us help you.

  • In my DB I have a state table with 19 states , or is the state code that is coming in the file . csv has to be one of them...I’m using Sqlbulkcopy to record this file in Bank...understood more or less ?

  • 1

    Avoid using HTML tags in the answer. To format as code, just select with the mouse and press the icon { }. For more details, please read this: http://answall.com/editing-help

1 answer

2


A possible solution would be:

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

if(!resultEstado) 
{ 
    Label3.Visible = true; 
    Label3.Text = "Campo Codigo Estado não esta vindo como valor inteiro"; 
}
else
{
    //abre conexao com o banco
    //faz a operação com o banco passando o campo 
    //id registro["Estado"]

    if(dr.HasRows())
    {
        Label3.Visible = true; 
        Label3.Text = "Campo Codigo Estado já existente no banco de dados"; 

    }
    else
    {
        // faz o insert
    }
}

In case you have doubts about how to do the operation with the bank answer then I help you.

Att.

  • So actually I’m passing this method to another method that this yes will records the file . csv in the database that method here oh: public void Processing(string path) { using (Sqlconnection connected = new Sqlconnection(Configurationmanager.Connectionstrings["Mc1_db_trainingconnectionstring"].Connectionstring) { connected.Open(); using (Sqlbulkcopy bc = Createsqlbulkcopy(connected)) { bc.Writetoserver(Returned filled(path)); } } }

  • 1

    @Daniel: when you want to add more information to the question, please edit it. So all the information is gathered in the body of the same.

  • Right, I’m sorry it’s my first day here

  • So Daniel, you do the flow shunt to check the id on the bank, like you’re already doing. If your primary condition is to know if the record comes from . csv is in the bank so add or not in the bank make the deviation already at the beginning and if the id exists in the bank, go to the next record in your .csv. If it was not clear help me understand your doubt. Att.

Browser other questions tagged

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