ExecuteNonQuery inside loop

我只是一个虾纸丫 提交于 2019-11-29 07:04:25

It looks like you are adding to the command's parameter collection over and over. Clear it with each iteration.

I would also suggest throwing the actual exception so you can see what the problem is.

Vaibhav Jain

I'm Telling you a simple solution & for sure it works. If you are using parameters in loop You need to clear the parameters after execution of query. So you can use that

cmd3.executeNonQuery();
cmd3.parameters.clear();

This is untested but should work as an alternative. Just add it once and continually update its value.

....
cmd3.Parameters.Add("@room_id", System.Data.SqlDbType.Int);

for (int i = 0; i < arrItemsPlanner.Length; i++)
{
    try
        {
            cmd3.Parameters["@room_id"].Value = 222;
            cmd3.ExecuteNonQuery();
        }
....

As an aside, your SqlCommand should be within a using block as well as your SqlConnection. The full code isn't shown so I don't know if your connection is actually done in such as way.

using (var conn = new SqlConnection(...))
using (var cmd = new SqlCommand(..., conn))
{

}

What you are doing is adding a parameter ever loop iteration. In the below code, it adds the parameter once, and just modifies the single parameter's value. Try this:

string query3 = "INSERT INTO furniture (room_id,member_id) VALUES (@room_id,333);"; 
SqlCommand cmd3 = new SqlCommand(query3, sqlConnection3);
cmd3.Parameters.Add("@room_id", SqlDbType.Int);

sqlConnection3.Open(); 

for (int i = 0; i < arrItemsPlanner.Length; i++) 
{ 
    try 
        { 
            cmd3.Parameters["@room_id"].Value = 222; 
            cmd3.ExecuteNonQuery(); 
        } 
        catch 
        { 
            return "Error: Item could not be saved"; 
        } 
        finally 
        { 
            //Fail 
        } 
    } 

Yes, don't add the parameter in the loop, only set its value:

string query3 = "INSERT INTO furniture (room_id,member_id) VALUES (@room_id,333);";
SqlCommand cmd3 = new SqlCommand(query3, sqlConnection3);
sqlConnection3.Open();

cmd3.Parameters.Add("@room_id", System.Data.SqlDbType.Int);

for (int i = 0; i < arrItemsPlanner.Length; i++)
{
    try
        {
            cmd3.Parameters["@room_id"].Value = 222;
            cmd3.ExecuteNonQuery();
        }
        catch
        {
            return "Error: Item could not be saved";
        }
        finally
        {
            //Fail
        }
    }
cmd3.Parameters.Add("room_id", System.Data.SqlDbType.Int);

// don't keep adding it in the loop either

cmd3.Parameters["room_id"].Value = 222; 

No @needed in the parameters collection whne using sql server

Another solution for those who are looking at this thread. Create two connections. One for your loop and another to send your NonQuery statements. This worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!