使用Parameters.AddWithValue发出问题并通过DataTable循环

时间:2014-01-28 18:08:23

标签: c# datatable

我有一个如下所示的DataTable:

[0]    [1]
"Z12"  "Company A"
"A32"  "Company B"
"K54"  "Company C"

我正在尝试遍历行,并使用以下代码将它们添加到Access表中:

OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\myDB.accdb");

OleDbCommand cmd = new OleDbCommand();

cmd.Connection = myConnection;
cmd.CommandType = CommandType.Text;

myConnection.Open();

for (int i = 0; i <= dt.Rows.Count - 1; i++)
    {
        cmd.CommandText = "INSERT INTO xCARRIER (CARRIER_ID, CARRIER_NAME) VALUES (@p1, @p2)";

        cmd.Parameters.AddWithValue("@p1", dt.Rows[i].ItemArray.GetValue(0));
        cmd.Parameters.AddWithValue("@p2", dt.Rows[i].ItemArray.GetValue(1));

        cmd.ExecuteNonQuery();
    }

myConnection.Close();

当我进入Access并查看xCARRIER表时,它看起来像这样:

"Z12"  "Company A"
"Z12"  "Company A"
"Z12"  "Company A"

当我单步执行代码时,看起来它正在循环遍历DataTable。我不知道为什么它会增加第一行3次。有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在每次迭代后清除Command参数:

 command.Parameters.Clear();

所以你的代码看起来像这样:

OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\myDB.accdb");

OleDbCommand cmd = new OleDbCommand();

cmd.Connection = myConnection;
cmd.CommandType = CommandType.Text;

myConnection.Open();

for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
    cmd.Parameters.Clear(); 
    cmd.CommandText = "INSERT INTO xCARRIER (CARRIER_ID, CARRIER_NAME) VALUES (@p1, @p2)";

    cmd.Parameters.AddWithValue("@p1", dt.Rows[i].ItemArray.GetValue(0));
    cmd.Parameters.AddWithValue("@p2", dt.Rows[i].ItemArray.GetValue(1));

    cmd.ExecuteNonQuery();
}

myConnection.Close();

或者只是更新以前的参数值:

for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
    cmd.CommandText = "INSERT INTO xCARRIER (CARRIER_ID, CARRIER_NAME) VALUES (@p1, @p2)";

    cmd.Parameters.AddWithValue["@p1"] = dt.Rows[i].ItemArray.GetValue(0));
    cmd.Parameters.AddWithValue["@p2"] = dt.Rows[i].ItemArray.GetValue(1));

    cmd.ExecuteNonQuery();
}