3
for (int i = 0; i < purchaseListView.Items.Count; i++)
Connection con = new Connection();
                 SqlCommand cmd = new SqlCommand();
                 SqlCommand cmdFifo = new SqlCommand();
                 con.OpenConnection();
                 cmd.Connection = con.DataBaseConnection;
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.CommandText = "insertDetail";
                 cmdFifo.Connection = con.DataBaseConnection;
                 cmdFifo.CommandType = CommandType.StoredProcedure;
                 cmdFifo.CommandText = "insertInToMain";

This is my code and I want to know if the loop affects performance of my software and if this is the right way to call stored procedure in loop.

I have stored the procedure in a class and I want to call it from a form when the save button is clicked and insert 10 items in the database via same stored procedure.

4

4 回答 4

0

您正在为每个非常低效的项目创建一个新的连接对象。

创建一个连接对象并n使用产品详细信息执行存储过程时间。或者,创建一个存储过程来接受 10 个项目并在该级别插入数据。

将其移到循环之外(您可以在不创建新实例的情况下访问循环内部concmd

  Connection con = new Connection();
  SqlCommand cmd = new SqlCommand();
  con.OpenConnection();
  cmd.Connection = con.DataBaseConnection;
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.CommandText = "insertDetail";

在循环中,您可以将所有参数添加到cmd对象。

 cmd.Parameters.Add("@Item", SqlDbType.Int);
 cmd.Parameters["@Item"].Value = purchaseListView.Items[i];
 cmd.ExecuteNonQuery();
于 2013-03-15T15:25:59.583 回答
0

好吧,您正在打开 10 个连接,而且您似乎没有关闭它们,所以您可能会用完连接,但我猜这不是整个代码,您可以发布整个 for 吗?

于 2013-03-15T15:27:48.070 回答
0

您应该在循环之前设置连接和存储过程,并且只更新命令参数值并在循环内执行。像这样:

Connection con = new Connection();
SqlCommand cmd = new SqlCommand();
SqlCommand cmdFifo = new SqlCommand();
con.OpenConnection();
cmd.Connection = con.DataBaseConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertDetail";
cmd.Parameters.Add("@Item", SqlDbType.Int); 
cmdFifo.Connection = con.DataBaseConnection;
cmdFifo.CommandType = CommandType.StoredProcedure;
cmdFifo.CommandText = "insertInToMain";
//now that your connections & commands are set up, you can reuse them within the loop
for (int i = 0; i < purchaseListView.Items.Count; i++)
{
    //ToDo:assign any SP parameter values
    cmd.Parameters["@Item"].Value = purchaseListView.Items[i]; 
    // ...

    //then exec within the loop
    cmd.ExecuteNonQuery();
    cmdFifo.ExecuteNonQuery();
}
于 2013-03-15T15:27:59.403 回答
0

我建议您创建一个表并通过遍历所有输入将整个数据插入其中,即尝试创建一个存储过程。多次运行 for 循环是低效的,并且数据库将生成结果集的次数,这也会由于网络开销而影响您的性能。

于 2013-03-15T15:32:16.990 回答