AddRange 取代 Add

时间:2022-02-14 08:55:14

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

''' ExecuteQuery,查询数据操作
''' </summary>
''' <param name="strSql">sql语句</param>
''' <param name="param">参数集合</param>
''' <param name="ct">命令类型</param>
''' <returns>DataTable类型,数据表</returns>
''' <remarks></remarks>
Public Function ExecuteQuery(ByVal strSql As String, ByVal param() As SqlParameter, ByVal ct As CommandType) As DataTable
Dim dt As New DataTable

comm = New SqlCommand(strSql, Me.GetConn)
comm.CommandType = ct

If param IsNot Nothing Then
For i = 0 To param.Length - 1
comm.Parameters.Add(param(i))
Next i
End If

Try
dr = comm.ExecuteReader()
dt.Load(dr)
Catch ex As Exception
Throw ex
Finally
dr.Close()
conn.Close()
End Try

Return dt
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