【发布时间】:2015-10-07 19:22:34
【问题描述】:
我正在使用下面的代码更新 SQL DB 中的一行。循环工作并更新行,但问题是每次通过循环时,它只更新一个值,而其他值被覆盖。所以最后,它已经更新,但不是为各个项目 ID 输入多个值到表中,而是只为各个项目 ID 输入一个值。我没有收到任何错误。非常感谢任何帮助。
for (int i = 0; i < cbAvailableEntities.Items.Count - 1; i++)
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("UpdateProjectEntity", connection);
using (connection)
{
connection.Open();
using (cmd)
{
if (cbAvailableEntities.Items[i].Selected)
{
cmd.CommandType = CommandType.StoredProcedure;
//the following is the Project ID for the row being updated.
SqlParameter paramPID = new SqlParameter("@ProjectID", nr.ProjectID);
cmd.Parameters.Add(paramPID);
nr.Entities = cbAvailableEntities.Items[i].Value;
cmd.Parameters.AddWithValue("@CorpID", nr.Entities);
cmd.ExecuteNonQuery();
}
}
}
}
这里是存储过程"UpdateProjectEntity"的SQL查询
ALTER PROCEDURE [dbo].[UpdateProjectEntity]
@ProjectID int,
@CorpID int
AS
BEGIN
UPDATE [dbo].[ProjectEntity]
SET
[CorpID] = @CorpID
WHERE
ProjectID = @ProjectID
END
这是我运行程序时输入和结果的屏幕截图。 These are the checkboxes I am saving to the DB
This is the result after I have saved to the DB
我更改了日期以表明该程序中的所有其他内容都正常。
【问题讨论】:
-
我不明白这个问题。你能展示一些正在发生的事情的数据吗?
-
btw 为什么要在循环内打开连接?如果您打开一次连接并执行所有命令然后关闭它会更好吗?
-
问题是每次执行查询时都会更新行。所以每次更新行时,它只用一个值更新它,然后当它完成循环时,只有最后一个值在 SQL 表中。因此,不是为一行更新多个值,而是只更新了一个值。
-
什么是
"UpdateProjectEntity"?如果那是一个 storeproc,你应该包含代码。 -
@JuanCarlosOropeza,我添加了存储过程的查询。
标签: c# mysql sql asp.net checkboxlist