2013-08-28 37 views
0

慢這是我對INSERT和UPDATE語句代碼:使用For循環在MySQL聲明獲得在vb.net

For i = 0 To lvFabric1.Items.Count - 1 

      strQ4 = "" 
      strQ4 = strQ4 & "INSERT into js_det(LINE_NO, FABRIC1, FABRIC2, `DESC`) SELECT LPAD('" & i + 1 & "',2, '0'), '" & lvFabric1.Items(i).Text & "','sdf', `DESC` from rm_inv where ITEM_CODE = '" & lvFabric1.Items(i).Text & "'" 

      strQ5 = "" 
      strQ5 = strQ5 & "UPDATE js_det set TRAN_NO = (SELECT JS_TRAN FROM counter) where Fabric1 = '" & lvFabric1.Items(i).Text & "'" 

      cmd.CommandText = strQ4 
      cmd.ExecuteNonQuery() 

      cmd.CommandText = strQ5 
      cmd.ExecuteNonQuery() 

     Next 

這裏的問題是什麼,它越來越慢,如果它是循環的5倍以上,它需要3秒以上。我怎樣才能加快這個代碼?還是有另一種方式?

感謝您的幫助。

回答

3

加快步伐,提交一氣呵成,整個事情,財產以後這樣的:

Dim sqls As New List(Of String) 
For i = 0 To lvFabric1.Items.Count - 1 
    sqls.Add("INSERT into js_det(LINE_NO, FABRIC1, FABRIC2, `DESC`) SELECT LPAD('" & i + 1 & "',2, '0'), '" & lvFabric1.Items(i).Text & "','sdf', `DESC` from rm_inv where ITEM_CODE = '" & lvFabric1.Items(i).Text & "'") 

    sqls.Add("UPDATE js_det set TRAN_NO = (SELECT JS_TRAN FROM counter) where Fabric1 = '" & lvFabric1.Items(i).Text & "'") 
Next 
If sqls.Any() Then 
    cmd.CommandText = sqls.Aggregate(Function(m, n) m & ";" & n) 
    cmd.ExecuteNonQuery() 
End If 

然而,這不是做sql查詢.NET中推薦的方式。

SQL參數應該用來避免任何sql注入或sql語法錯誤。

編輯:使用SQL參數 -

Using con As New SqlConnection("My connection string..."), 
     cmd As New SqlCommand(sql, con) 
     cmd.CommandText = "UPDATE js_det set TRAN_NO = (SELECT JS_TRAN FROM counter) where Fabric1 = @fabric" 
     Dim fabricParam = cmd.Parameters.Add("@fabric", SqlDbType.VarChar) 

     con.Open() 
     For i = 0 To lvFabric1.Items.Count - 1 
      fabricParam.Value = lvFabric1.Items(i).Text 
      cmd.ExecuteNonQuery() 
     Next 
     con.Close() 

    End Using 
+0

啊好吧,先生,我會嘗試這一個,TNX – Matthew

+0

它提高了大約兩秒鐘,感謝您對本! – Matthew