Insert data from the DataSet into a database

1

I have the following code:

using System;
using System.Linq;
using FirebirdSql.Data.FirebirdClient;
using System.Configuration;
using System.Data;

namespace TblCliente
{
    public class Program
    {
        static void Main(string[] args)
        {
            FbConnection fbConnectionPrincipal = new FbConnection
            {
                ConnectionString = ConfigurationManager.ConnectionStrings["strFirebirdPrincipal"].ToString()
            };
            FbConnection fbConnectionSecundaria = new FbConnection
            {
                ConnectionString = ConfigurationManager.ConnectionStrings["strFirebirdSecundaria"].ToString()
            };

            FbDataAdapter fbDataAdapterPrimario = new FbDataAdapter("SELECT * FROM PRODUTO WHERE PRODUTO.CODPROD = '000399'", fbConnectionPrincipal);
            FbDataAdapter fbDataAdapterSecundario = new FbDataAdapter("SELECT * FROM PRODUTO WHERE PRODUTO.CODPROD = '000399'", fbConnectionSecundaria);

            DataTable dataTableP = new DataTable();
            DataTable dataTableS = new DataTable();

            fbDataAdapterPrimario.Fill(dataTableP);
            fbDataAdapterSecundario.Fill(dataTableS);

            dataTableP.Merge(dataTableS);

            var Produto = dataTableP.AsEnumerable().Distinct();


            Console.ReadKey();

        }
    }
}

This code returns results from two distinct databases and included in DataSet different, after that I made a DataSet.Merge and on it different values were returned. How do I include these distinct lines in a new database?

    
asked by anonymous 12.09.2018 / 21:57

1 answer

0

If you already have all the information stored in DataTable then you will need to insert it into the database:

private void InsertData(dynamic fbCon, string table, List<(string Field, dynamic Value)> parameters)
{
    string fields = string.Join(", ", parameters.Select(r => r.Field));
    string values = string.Join(", ", parameters.Select(r => $"@{r.Field}"));
    string sql = $"INSERT INTO {table}({fields}) VALUES({values})";

    FbCommand fbCom = new FbCommand(sql, fbCon);

    foreach (var parameter in parameters)
        fbCom.Parameters.AddWithValue(parameter.Field, parameter.Value);

    fbCom.ExecuteNonQuery();
}

This method can be used in most cases, and the way to use it is something like this:

var list = new List<(string Field, dynamic Value)>();

list.Add((Field: "price", Value: 10));
list.Add((Field: "name", Value: "teste"));
list.Add((Field: "date", Value: DateTime.Today));

InsertData(null, "products", list);
    
13.09.2018 / 12:28