C# convert Array for insertion in the database

Asked

Viewed 135 times

0

I have a Array, some of the values of this array will be added as float others like int, my doubt is the following, as I can convert only one array not the whole list?

I would have to create a variable to receive this value and convert? or would have a simpler way?

static void Main(string[] args)
    {
        string procurar = "|";
        int Converter;
        StreamReader Arquivo = new StreamReader(@"C:\log\meutxt.txt");
        string[] arrValores = new string[48]; //48
        SqlConnection conexao = new SqlConnection(@"Password=Azeite10;Persist Security Info=True;User ID=sa;Initial Catalog=bdTeste;Data Source=DESKTOP-G8JGBNC");/*@"Password=Azeite10;Persist Security Info=True;User ID=sa;Initial Catalog=bdTeste;Data Source=SCAN-D-50985\SQL"*/
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conexao;
        conexao.Open();
        Console.WriteLine("Carregando...");
        while (Arquivo.Peek() != -1)
        {
            var strLinha = Arquivo.ReadLine().Split('|');

            arrValores[0] = strLinha[1];
            arrValores[1] = strLinha[2];
            arrValores[2] = strLinha[3];
            arrValores[3] = strLinha[4];



            cmd.CommandText = string.Format("INSERT INTO [dbo].[123] VALUES ('{0}','{1}','{2}','{3}')", strLinha[1], strLinha[2], strLinha[3], strLinha[4].ToString());
            cmd.ExecuteNonQuery();
        }

    }

my text file in the final process returns me a line like this.

|2021549040    |000001                     |0001                    |MTO                       |ZXDC            |5034293         |ASIAN AMERICAN METALS, INC.        |5034293               |ASIAN AMERICAN METALS, INC.        |6126585         |LPL 3003 H14 1,600X1219,2X3048 C-CC-EE  |PO343610 - BALTIMORE               |        23,859 |KG            |      23.859,000 |        23.859,000 |         0,000 |Z)            |               29.217,000 |                   0,000 |                  0,000 |       0,000 |22.12.2017        |2020       |C              |18.04.2018|27.07.2018        |27.07.2018     |26.07.2018         |27.07.2018           |             |2200                 |OUTROS ME      |LCC01001         |CC ME                         |                    |                           |               |Laminados         |BANACM       |          |                                    |CIP-BALTIMORE                 |               0,000 |                             |2020              |

where the | "CONTENTS"

Tables in the database

[dbo].[1234]
       ([Ordem de venda]
       ,[Item do documento de vendas]
       ,[N. da divisão de remessa]
       ,[Estratégia]
       ,[Tipo Doc. Vendas]
       ,[Emissor da Ordem]
       ,[Nome do Cliente]
       ,[Cód. Receb. Mercadoria]
       ,[Receb. Mercadoria]
       ,[Cód. do Material]
       ,[Desc. do Material]
       ,[N. Pedido do Cliente]
       ,[Qtde Item Ordem]
       ,[Unidade Medida]
       ,[Qtde Item Divisão]
       ,[Quantidade Faturada]
       ,[Saldo a faturar]
       ,[Ctg de Divisão]
       ,[Quantidade Produzida (MTO)]
       ,[Qtd. em Estoque (Fábrica)]
       ,[Estoque para Centro (CD)]
       ,[Estoque (901)]
       ,[Data de criação OV]
       ,[Centro (CD)]
       ,[Status da Ordem]
       ,[Data GRD]
       ,[1ª. Data Prometida]
       ,[Data de Entrega]
       ,[Data prep. material]
       ,[Data saída mercadoria]
       ,[Motivo Recusa]
       ,[Organização de Vendas]
       ,[Cta. no Cliente]
       ,[Vlr.Fam.Orçamento]
       ,[Desc.Fam.Orçamento]
       ,[Observação]
       ,[Cod.Fixação Ordem Planejada]
       ,[Lista de anexos]
       ,[Desc.Fam.Expedição]
       ,[Criador da OV]
       ,[Itinerário]
       ,[Descrição do transito]
       ,[INCOTERMS]
       ,[Quantidade em remessa]
       ,[Comprimento]
       ,[Local de expedição])
  • This code does not make sense, it is extremely insecure and the question does not give enough details to give an adequate answer, including mentioning things that you can not notice in the code. Need to improve the question to understand the problem.

  • simple my array gets 48 lines, I have to enter this data in the database, however I need to convert some to float or date, because without converting the sql does not insert in the database, I put my entire code, is not complete yet, this list arrValores[ goes up to 48]

  • You could put the layout of the text file and the fields of your database?

  • edited my question with this information.

1 answer

0


William, I changed your code the way below to accomplish the task and resolve the issue of conversions.

I modified your query to use parameters.

In the loop, the values of the parameters are defined, with their respective type conversions, considering that the layout of the lines of your file, with respect to the type of each column, is always the same.

Note that in the code below I used only 5 fields, to simplify the example.

With this implementation you can apply the conversions without the need to create variables to store the data.

using System;
using System.IO;
using System.Data.SqlClient;

public class Program
{    
    public static void Main(string[] args)
    {
        StreamReader Arquivo = new StreamReader(@"C:\log\meutxt.txt");

        SqlConnection conexao = new SqlConnection(@"Password=Azeite10;Persist Security Info=True;User ID=sa;Initial Catalog=bdTeste;Data Source=DESKTOP-G8JGBNC");/*@"Password=Azeite10;Persist Security Info=True;User ID=sa;Initial Catalog=bdTeste;Data Source=SCAN-D-50985\SQL"*/
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conexao;
        conexao.Open();

        Console.WriteLine("Carregando...");

        // Definição da query que será executada.
        cmd.CommandText = "INSERT INTO [dbo].[123] VALUES (@par1, @par2, @par3, @par4, @par5)";

        while (Arquivo.Peek() != -1)
        {
            var strLinha = Arquivo.ReadLine().Split('|');

            // Limpa a lista de parâmetros para nova definição destes a cada iteração, uma vez que os valores dos parâmetros sofrerão alterações.
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@par1", Convert.ToDouble(strLinha[1])); // Campo do tipo Double.
            cmd.Parameters.Add("@par2", Convert.ToInt32(strLinha[2]));  // Campo do tipo Int.
            cmd.Parameters.Add("@par3", Convert.ToInt32(strLinha[3]));
            cmd.Parameters.Add("@par4", strLinha[4]);                   // Campo do tipo String. Não requer conversão pois strLinha já é do tipo string.
            cmd.Parameters.Add("@par5", strLinha[5]);

            cmd.ExecuteNonQuery();
        }

        conexao.Close();
    }
}

If the above solution doesn’t suit you, let us know to try to help again.

  • exactly what I needed, thank you very much!

Browser other questions tagged

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