I am looking for a way to import a load of variables computed in a foreach loop into my database. I am creating an application that extracts values from plain text (.txt files). In the example below, I filter the value from a text string. I want the application to automatically insert each value (after calculation) from the loop into a new row in the database table. Does anyone know what is the best way to do this, and how to do it?
foreach (string resultregel in mtregel) { <br /><b>Rij: @regnr</b><br /> regnr = regnr + 1; string valuedateimportA = resultregel.Remove(6); if (valuedateimportA.StartsWith("0")) { var valuedateimport = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); <i>Value Date Import = No ValueDateImport found!!</i><br /> } else { DateTime valuedateimportB = DateTime.ParseExact(valuedateimportA, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture); string valuedateimport = valuedateimportB.ToString("dM-yyyy"); <i>Value Date Import = @valuedateimport</i><br /> } }
I tried to add this code, but it does not work:
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString) { System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("INSERT INTO Import_table (valuedateimport, description, valuename) VALUES (@valuedateimport, @description, @valuename)"); cmd.CommandType = System.Data.CommandType.Text; cmd.Connection = connection; cmd.Parameters.AddWithValue("@valuedateimport", txtvaluedateimport.Text); cmd.Parameters.AddWithValue("@description", txtdescription.Text); cmd.Parameters.AddWithValue("@valuename", txtvaluename.Text); connection.Open(); cmd.ExecuteNonQuery(); }
source share