I'm trying to add data into a database using a foreach loop to iterate through lists which contain values of different types.
List<string> productCodeList = new List<string>();
List<string> productNameList = new List<string>();
List<string> productPriceList = new List<string>();
List<int> competitorList = new List<int>();
List<DateTime> dateCreatedList = new List<DateTime>();
Is there a way to iterate through multiple lists with different types? Because at the moment I'm only able to insert one list to one column. What I want is to insert data to all the columns specified.
Or is there possibly a better way of doing this?
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(@"INSERT INTO OnlineProductsTemp$(CompetitorID, ProductCode, ProductName, Price, DateCreated)
VALUES(@CompetitorID, @ProductCode, @ProductName, @Price, @DateCreated)", con))
{
cmd.Parameters.Add("@CompetitorID", SqlDbType.Int);
cmd.Parameters.Add("@ProductCode", SqlDbType.VarChar);
cmd.Parameters.Add("@ProductName", SqlDbType.VarChar);
cmd.Parameters.Add("@Price", SqlDbType.Decimal);
cmd.Parameters.Add("@DateCreated", SqlDbType.DateTime);
foreach (var value in competitorList)
{
cmd.Parameters["@CompetitorID"].Value = value;
int rowsAffected = cmd.ExecuteNonQuery();
}
competitorList.Clear();
}
}
Thanks in advance!