数据插入循环不起作用

时间:2017-08-10 13:54:08

标签: c# sql-server

this question相关:我正在尝试编写一个“INSERT”循环:我有以下查询:

CommandText = "INSERT into sample2Prot(timestp,idq,idz,prot,Lhowmany,Rhowmany) VALUES(@timestp,@idq,@idz,@prot,@Lhowmany,@Rhowmany)";

当我执行我的代码(可以在下面找到)时,我收到以下错误:

  

'@ timestp'无法由SqlParameterCollection处理。 (“timestp”= tableNames [0],字符串类型)

for (int j = 0; j < tableNames.Count; j++)

// tableNames contains the name of the columns, tableTypes the types of the columns
// tableTypes contains
{
     if (tableTypes[j] == "INTEGER")
     {
           myCommand3.Parameters.Add("@" + tableNames[j], System.Data.SqlDbType.Int);
           Console.WriteLine("@" + tableNames[j]);
     }
     else
     {
           myCommand3.Parameters.Add("@" + tableNames[j], System.Data.SqlDbType.VarChar);
           Console.WriteLine("@" + tableNames[j]);
     }

}

Console.WriteLine(myCommand3.CommandText);
for (int f = 0; f < total.Count(); f++)
{
     for (int k = 0; k < tableNames.Count; k++)
     {
           myCommand3.Parameters.Clear();
           myCommand3.Parameters["@" + tableNames[k]].Value = total[f][k];
     }

     myCommand3.ExecuteNonQuery();
}

有人有想法吗?不要在于要求更高的精确度。

1 个答案:

答案 0 :(得分:1)

for (int f = 0; f < total.Count(); f++)
{
     for (int k = 0; k < tableNames.Count; k++)
     {
           myCommand3.Parameters.Clear(); // < ==== PROBLEM is here!
           // After clearing the Parameters, there is no Parameter "["@" + tableNames[k]]"
           // hence "SqlParameter mit ParameterName '@timestp' ist nicht in SqlParameterCollection enthalten."
           // (eng: SqlParameterCollection does not contain SqlParameter with name '@timestp' )
           myCommand3.Parameters["@" + tableNames[k]].Value = total[f][k];
     }

     myCommand3.ExecuteNonQuery();
}

在上面的代码中,移动Clear()语句,如下所示:

for (int f = 0; f < total.Count(); f++)
{
     for (int k = 0; k < tableNames.Count; k++)
     {
           myCommand3.Parameters["@" + tableNames[k]].Value = total[f][k];
     }
     myCommand3.ExecuteNonQuery();
}
myCommand3.Parameters.Clear();