必须声明标量变量(C# 和 OleDb)

Must declare a scalar variable (C# and OleDb)

我知道这个问题已经被问过好几次了,但是 none 的答案帮助我解决了这个问题。

所以,我正在编写数据传输实用程序,将数据从一个 table 的 OleDb 数据库复制到另一个 table 的 OleDb 数据库。

我已经从源数据库中读取了所有数据,并且正在尝试写入,但总是出现此错误

Must declare the scalar variable "@CategoryID"

这是代码

 // generating the insert string below
 string insert = "INSERT INTO Categories VALUES (";
 for(int i = 0; i < cols.Length; i++)
 {
     string coma = ", ";
     if (i == cols.Length - 1)
     coma = " )";

     insert += "@" + cols[i] + coma;
 }

try
{ 
    while (src_reader.Read())         // reading from source database
    {
        dstcmd.CommandText = insert;   

        for (int i = 0; i < cols.Length; i++)
        {
            string temp = "@" + cols[i];     // cols is array of column names
            dstcmd.Parameters.AddWithValue(temp, src_reader[cols[i]]);

            // for debug purposes... below is screenshot of error
            Console.Write(temp + "  " + src_reader[cols[i]] + "\n");
        }

        Console.WriteLine("");

        // point of error
        dstcmd.ExecuteNonQuery();
    }
}
catch(Exception ex)
{
    Console.WriteLine(ex);
}

错误截图如下。

CategoryID 是 table 的第一列,因此是插入的第一个值。

如有任何帮助,我们将不胜感激。如果我遗漏了任何信息或有任何不合理之处,请告诉我。

尝试更改此部分:

// generating the insert string below
 string insert = "INSERT INTO Categories VALUES (";
 for(int i = 0; i < cols.Length; i++)
 {
     string coma = ", ";
     if (i == cols.Length - 1)
     coma = " )";

     insert += "@" + cols[i] + coma;
 }

// generating the insert string below
 string insert = "INSERT INTO Categories VALUES (";
 for(int i = 0; i < cols.Length; i++)
 {
     string coma = ", ";
     if (i == cols.Length - 1)
     coma = " )";

     insert += "?" + coma;
 }

您不需要在 VALUES 中使用参数名称,而只需使用 ? 占位符。但是,请确保添加参数时的参数顺序与 table.

中列的顺序相匹配

此外,最好在 INSERT 子句中显式指定列列表,例如:

string insert = "INSERT INTO Categories (Col1, Col2, Col3, etc.)  VALUES (";

看看您是否也想使该列名列表也动态生成。但我建议先让它为静态列列表工作,然后再将其转换为动态版本。

此外,如果您没有为 INSERT 指定列名称列表,您将为所有列指定值。