c# Entering data from list into Access Database with foreach results in duplicated values in all rows

676 views Asked by At

I am attempting to input a list from C# to an Access Database. However when it get input all of the rows have the exact same values. I can do a console write in the for each and show that it is getting the correct values, it's just writing the same thing over and over. Any help would be greatly appreciated!!

Here is the code and screenshots,

    public static void BuildMerakiTemplateList(string client, IList<MerakiApi.ConfigTemplates> templateList)
    {
        using (
            var conn =
                new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" +
                                    @"Data Source=" + UniversalVariables.ConfigShare + @"CustomerLanInfo.accdb")
        )
        {
            OleDbCommand cmd = null;
            cmd = new OleDbCommand("INSERT into [Meraki Templates](ClientID, TemplateName, TemplateID) values (?, ?, ?)", conn);
            conn.Open();
            foreach (MerakiApi.ConfigTemplates template in templateList)
            {
                Console.WriteLine(template.name + " " + template.id);
                cmd.Parameters.Add("@ClientID", OleDbType.VarChar).Value = client;
                cmd.Parameters.Add("@TemplateName", OleDbType.VarChar).Value = template.name;
                cmd.Parameters.Add("@TemplateID", OleDbType.VarChar).Value = template.id;
                cmd.ExecuteNonQuery();
            }
        }
    }

Console output of code

View of entries in database

1

There are 1 answers

0
Koby Douek On

When creating a string to use a SQL with parameters, you don't use ? as the command parameter name, you need to pass the @paramName - with a @ sign:

cmd = new OleDbCommand("INSERT into [Meraki Templates](ClientID, TemplateName, TemplateID) values (@ClientID, @TemplateName, @TemplateID)", conn);

Then, when you add the command parameters, you add the parameters wintout the @ sign:

cmd.Parameters.Add("ClientID", OleDbType.VarChar).Value = client;
cmd.Parameters.Add("TemplateName", OleDbType.VarChar).Value = template.name;
cmd.Parameters.Add("TemplateID", OleDbType.VarChar).Value = template.id;
cmd.ExecuteNonQuery();