可能重复:
变量名'@VarName'已被声明为Issue
using (SqlCommand command = connection.CreateCommand())
{
int j = 1;
for (int i = 0; i < temp4.Count; i++)
{
#region idsetter
int prevId = 0;
command.CommandText = "SELECT MAX(id) FROM Configuration";
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (reader[0].ToString() != "")
{
prevId = Int32.Parse(reader[0].ToString());
}
else
{
prevId = 0;
}
}
}
connection.Close();
int currId = prevId + 1;
#endregion
command.CommandText = "INSERT INTO Configuration (id,A, B, C, D, E, F,G) " +
"VALUES (@id, @a, @b , @c, @d, @e, @f, @g)";
command.Parameters.AddWithValue("@id", currId);
command.Parameters.AddWithValue("@a", myL);
command.Parameters.AddWithValue("@b", pipi);
command.Parameters.AddWithValue("@c", temp4[i].ad);
command.Parameters.AddWithValue("@d", temp4[i].asa);
command.Parameters.AddWithValue("@e", temp4[i].Tasa);
command.Parameters.AddWithValue("@f", j);
command.Parameters.AddWithValue("@g", 1);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
j++;
if (j > 7)
{
j = 1;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图在配置表中首先读取id并增加它然后写入其他所有内容.但是当添加第二个条目时,它会给出异常
变量名"@id"已经声明.变量名在查询批处理或存储过程中必须是唯一的.
如何避免这种异常的任何解决方法?
如果每次添加相同的参数,那么它总是会给你一个例外.
在for循环之前声明变量并给它们一些默认值,如:
command.Parameters.AddWithValue("@id", 1);
command.Parameters.AddWithValue("@a", "");
command.Parameters.AddWithValue("@b", "");
command.Parameters.AddWithValue("@c", "");
command.Parameters.AddWithValue("@d", "");
command.Parameters.AddWithValue("@e", "");
command.Parameters.AddWithValue("@f", 1);
command.Parameters.AddWithValue("@g", 1);
Run Code Online (Sandbox Code Playgroud)
然后改变后的参数的值command.CommandText = "INSERT INTO Configuration (id,A, B, C, D, E, F,G) VALUES (@id, @a, @b , @c, @d, @e, @f, @g)";等
cmd.Parameters["@id"].Value=currId;
cmd.Parameters["@a"].Value=myL;
cmd.Parameters["@b"].Value=pipi;
cmd.Parameters["@c"].Value=temp4[i].ad;
cmd.Parameters["@d"].Value=temp4[i].asa;
cmd.Parameters["@e"].Value=temp4[i].Tasa;
cmd.Parameters["@f"].Value=j;
cmd.Parameters["@g"].Value=1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1199 次 |
| 最近记录: |