Insert Dataset data into database

Asked

Viewed 97 times

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 brings results from two distinct databases and included in DataSet different, after that I made a DataSet.Merge and on top of it were returned the distinct values. How do I include these distinct lines in a new database ?

  • 1

    Opening a new connection and doing the Insert?

  • This new connection would be the fbConnectionSecundaria!

  • 2

    Then just write the insert using the fbConnectionSecundaria even...

1 answer

0

If you already have all the information stored on DataTable then the need will be to enter it in 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);

Browser other questions tagged

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