implode of columns and rows of DataTable C #

0

I am trying to make a data insertion, of a dataTable whose data has been passed from an sql query, I want to dump this data into another table, as they come.

This function will do it for several tables, so the column names and the quantity can not be defined in the code. the idea is to execute a query like the following.

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

In php there is the solution to make an implode to the results.

$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO 'fbdata'($columns) VALUES ($values)";

But in C # I have no idea how to do the implode

This is the code I have.

SqlDataReader datosAnfitrion = origen.ExecuteQuerySelect("Select * from "+datosFila.TablaOrigen+" "+datosFila.CondOrigen);
                DataTable schemaTable = datosAnfitrion.GetSchemaTable();

                var columnas= string.Join(",", schemaTable.AsEnumerable().Select(T =>
                T.ColumnName.ToString()).ToArray());

However, I think that code needs to specify the name of the column

    
asked by Aquiles Perez 22.09.2017 в 18:08
source

1 answer

1

If someone serves, I found the solution

SqlDataReader datosAnfitrion = origen.ExecuteQuerySelect("Select * from mitabla");
            DataTable dt= new DataTable();
            dt.Load(datosAnfitrion);
            var columns = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();
            var columnsParams = columns.Select(x => $"@{x}").ToList();
            var insertSql = $"INSERT INTO {datosFila.TablaDestino} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", columnsParams)});";

            foreach (DataRow dr in dt.Rows)
             {

                using (MySqlCommand msc = new MySqlCommand(insertSql, destino.cnn))
                {
                    foreach (var column in columns) msc.Parameters.AddWithValue(column, dr[column]);                        
                    msc.ExecuteNonQuery();
                }

             }
    
answered by 25.09.2017 / 17:39
source