AddRange 取代 Add

cmd.Parameters的Add方法是增加一个参数,增加多个参数的的时候使用一个foreach循环,cmd.Parameters的AddRange方法是增加一个参数的数组。

Add:将指定的对象添加到……中

AddRange:向……末尾,添加数组

在群体操作时,使用AddRange取代Add

用AddRange可以让我们要加入的东西一次性加入,而不要每次只加一个,这样显然可以加快速度。几乎所有的windows control都支持Add和AddRange两种方法。

Add:

For i = 0 To param.Length - 1
comm.Parameters.Add(param(i))
Next i
 

AddRange: 

Comm.Parameters.AddRange(Param)

支持Add和AddRange的类:
StringCollection, TraceCollection, SqlParameter, etc.
HttpWebRequest
UserControl
ColumnHeader

原代码:

 
  1. ''' ExecuteQuery,查询数据操作
  2. ''' </summary>
  3. ''' <param name="strSql">sql语句</param>
  4. ''' <param name="param">参数集合</param>
  5. ''' <param name="ct">命令类型</param>
  6. ''' <returns>DataTable类型,数据表</returns>
  7. ''' <remarks></remarks>
  8. Public Function ExecuteQuery(ByVal strSql As String, ByVal param() As SqlParameter, ByVal ct As CommandType) As DataTable
  9. Dim dt As New DataTable
  10. comm = New SqlCommand(strSql, Me.GetConn)
  11. comm.CommandType = ct
  12. If param IsNot Nothing Then
  13. For i = 0 To param.Length - 1
  14. comm.Parameters.Add(param(i))
  15. Next i
  16. End If
  17. Try
  18. dr = comm.ExecuteReader()
  19. dt.Load(dr)
  20. Catch ex As Exception
  21. Throw ex
  22. Finally
  23. dr.Close()
  24. conn.Close()
  25. End Try
  26. Return dt
  27. End Function

 

 

修改后:

 
  1. ''' <summary>
  2. ''' 查询方法
  3. ''' </summary>
  4. ''' <param name="myCommandType">sql语句类型:区别于存储过程</param>
  5. ''' <param name="Param">参数数组</param>
  6. ''' <param name="strSql">sql语句</param>
  7. Public Function ExecuteQuery(ByVal myCommandType As CommandType, ByVal Param() As SqlParameter, ByVal strSql As String) As DataTable
  8. Dim dt As New DataTable
  9. Comm = New SqlCommand(strSql, Me.GetConn)
  10. Comm.CommandType = myCommandType
  11. If Param IsNot Nothing Then
  12. Comm.Parameters.AddRange(Param)
  13. End If
  14. Try
  15. myDataReader = Comm.ExecuteReader
  16. dt.Load(myDataReader)
  17. Catch ex As Exception
  18. Throw ex
  19. Finally
  20. myDataReader.Close()
  21. Conn.Close()
  22. End Try
  23. Return dt
  24. End Function
posted @ 2014-11-23 11:33  net5x  阅读(376)  评论(0编辑  收藏  举报