Search code examples
c#sqloledbado

from list<> to database records is repeating


I have the following code to create a list<> with three records and populate an access database with this list. It works but the database is populated with the list's first record three times, i.e., the rows are repeated. Any help would be greatly appreciated. Thank you

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<Project>(){
                new Project{ProjectId="ID1",ProjectName="AAAA"}, 
                new Project{ProjectId="ID2",ProjectName="BBBB"},
                new Project{ProjectId="ID3",ProjectName="CCCC"},
            };


            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\td\Desktop\Test2.accdb";
            OleDbConnection con = new OleDbConnection(connectionString);
            string accessQuery = "INSERT INTO [table] (ProjectId, ProjectName) VALUES (@ProjectId, @ProjectName)";
            OleDbCommand cmd = new OleDbCommand(accessQuery, con);

            con.Open();


            for (int i = 0; i < list.Count; i++)
            {
                cmd.Parameters.AddWithValue("@ProjectId", list[i].ProjectId);
                cmd.Parameters.AddWithValue("@ProjectName", list[i].ProjectName);
                cmd.ExecuteNonQuery();
            }

        }
    }

    public class Project
    {
        public string ProjectId { get; set; }
        public string ProjectName { get; set; }
    }
}

Solution

  • You are creating the command outside your for loop and then attempting to add the parameters to the same command. I am guessing that when you call cmd.Parameters.AddWithValue for i > 0 those values are being silently ignored. Try

    string accessQuery = "INSERT INTO [table] (ProjectId, ProjectName) VALUES (@ProjectId, @ProjectName)";
    OleDbCommand cmd = new OleDbCommand(accessQuery, con);    
    con.Open();
    
    for (int i = 0; i < list.Count; i++)
    {
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@ProjectId", list[i].ProjectId);
        cmd.Parameters.AddWithValue("@ProjectName", list[i].ProjectName);
        cmd.ExecuteNonQuery();
    }
    

    If that doesn't work (not at my dev machine, I can't test right now), you can always move the command creation inside your for loop and leave everything else the same.