简体   繁体   中英

update function (AddWithValue parameter included) won't work

Im trying to loop over some array, and through that , update with new parameters..

this is my code :

for (int i = 0; i < wholeArr.Length - 1; i++)
    {
        string[] temp = wholeArr[i].Split('-');
        UpdateQuery(int.Parse(temp[1]), int.Parse(temp[0]));



    }

and this is my update function :

public void UpdateQuery(int id, int newOrder)
{
    string sql = "update Tama38News set [OrderingNumber] = @OrderingNumber where [ID] = @ID";

    con = new SqlConnection(connection);
    con.Open();
    adapter = new SqlDataAdapter();
    command = new SqlCommand(sql, con);
    command.Parameters.AddWithValue("@ID", id);
    command.Parameters.AddWithValue("@OrderingNumber", newOrder);

    command.ExecuteNonQuery();
    con.Close();
}

the thing is, Im not getting any exception, but for some reason the DB doesnt get affected..

any idea why ?

Are you sure that you want to omit the last item in the array?

Change wholeArr.Length - 1 to wholeArr.Length

for (int i = 0; i < wholeArr.Length; i++)
{
    string[] temp = wholeArr[i].Split('-');
    UpdateQuery(int.Parse(temp[1]), int.Parse(temp[0]));
}

Maybe there was only one item, hence the method UpdateQuery was never called. You can use the debugger to check what's going on. Set a breakpoint in the loop and press F10 to go to the next line. Inspect values in the quick-watch-window.

Apart from that, you should always dispose anything that implements IDisposable especially connections best with using-statement .

public void UpdateQuery(int id, int newOrder)
{
    string sql = "update Tama38News set [OrderingNumber] = @OrderingNumber where [ID] = @ID";
    using(var con = new SqlConnection(connection))
    {
        using(var command = new SqlCommand(sql, con))
        {
            con.Open();
            command.Parameters.AddWithValue("@ID", id);
            command.Parameters.AddWithValue("@OrderingNumber", newOrder);
            command.ExecuteNonQuery();
        }
    }
}

确保temp [1]实际上是您想要的ID,而temp [0]是newOrder ID,并且不要将它们混在一起。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM