我在SQL Server中迭代incidentNoReserve
tbl。单击按钮时,如果它与变量匹配,则整行将从incidentNoReserve
tbl中删除。
这是代码:
private void button3_Click(object sender, EventArgs e)
{
try
{
using (var cmd106 = new SqlCommand("select * from [dbo].[incidentNoReserve]", cnn))
{
cnn.Open();
SqlDataReader reader = cmd106.ExecuteReader();
while (reader.Read())
{
var commonNo = reader["incidentNoReserveId"];
//Every new row will create a new dictionary that holds the columns
if (Convert.ToInt16(commonNo) == newLastIncidentNo )
{
var cmd107 = new SqlCommand("Delete from[dbo].[incidentNoReserve] where incidentNoReserveId = @newLastIncidentNo", cnn);
cmd107.Parameters.AddWithValue("@newLastIncidentNo", newLastIncidentNo);
cmd107.ExecuteNonQuery();
}
cnn.Close();
}
reader.Close();
}
}
catch (Exception ex)
{
// If an exception occurs, write it to the console
Console.WriteLine(ex.ToString());
}
finally
{
cnn.Close();
}
this.Close();
}
newLastIncidentNo
有18个,当它到达commonNo时它有10个,它只是incidentNoReserve
表中的第一行。
可能是什么问题?
答案 0 :(得分:0)
您正在关闭 循环
中的连接您正在使用相同的连接来循环和更新
答案 1 :(得分:-1)
它工作我刚刚删除了内部打开和关闭连接。谢谢所有
答案 2 :(得分:-1)
我这样修理:
while (reader.Read())
{
int commonNo = Convert.ToInt16(reader["incidentNoReserveId"]);
//Every new row will create a new dictionary that holds the columns
if (Convert.ToInt16(commonNo) == newLastIncidentNo)
{
reader.Close();
//newLastIncidentNo = (Convert.ToInt16(commonNo));
using (SqlCommand command = new SqlCommand("Delete from [dbo].[incidentNoReserve] where incidentNoReserveId = @newLastIncidentNo", cnn))
{
//MessageBox.Show(newLastIncidentNo.ToString());
command.Parameters.AddWithValue("@newLastIncidentNo", newLastIncidentNo);
command.ExecuteNonQuery();
}
}
}
cnn.Close();
}
}
catch (Exception ex)