SqlParameter已包含在另一个SqlParameterCollection中

时间:2016-01-24 08:21:28

标签: sql vb.net visual-studio-2010 stored-procedures parameter-passing

以下是我的全名 DataAccessLayer

  • 问题是当我添加多个参数时,它们具有相同的名称 即使我确实将它们添加到我的名为 paramlist 的arraylist中,但名字却截然不同
  • 因为我正在接收"当我调用 setParameter sub时,SqlParameter已被另一个SqlParameterCollection" 错误包含
  • 在添加一组新参数之前,我在参数列表 cmd 中清除了参数
Imports System.Data
Imports System.Data.SqlClient

Public Class DataAccessLayer
    Public cmd As New SqlCommand
    Dim conn As New SqlConnection
    Dim da As New SqlDataAdapter
    Dim dt As New DataTable
    Dim param As New SqlParameter
    Dim paramlist As New ArrayList
    Public Sub connectToDB()
        cmd = New SqlCommand
        conn = New SqlConnection
        conn.ConnectionString = "Data Source=10.10.30.104\CGHMSSQL;Initial Catalog=dbPractice;User ID=sa;Password=12345"
        conn.Open()
        cmd.Connection = conn
        cmd.CommandType = CommandType.StoredProcedure
    End Sub
    Public Function getDataTable(ByVal storedProc As String) As DataTable
        connectToDB()
        da = New SqlDataAdapter
        dt = New DataTable
        cmd.CommandText = storedProc
        dt.Clear()
        setParameter(cmd)
        da.SelectCommand = cmd
        da.Fill(dt)
        Return dt
    End Function
    Public Sub executeQuery(ByVal storedProc As String)
        connectToDB()
        cmd.CommandText = storedProc
        setParameter(cmd)
        cmd.ExecuteNonQuery()
    End Sub
    Public Sub setParameter(ByVal cmd As SqlCommand)
        For Each param As SqlParameter In paramlist
            cmd.Parameters.Add(param)
        Next
    End Sub
    Public Sub addParameter(ByVal parameterName As String, ByVal dbType As DbType, ByVal value As Object)
        param.ParameterName = parameterName
        param.DbType = dbType
        param.Direction = ParameterDirection.Input
        param.Value = If((value Is Nothing), DBNull.Value, value)
        paramlist.Add(param)
    End Sub
    Public Sub clearParameters()
        paramlist.Clear()
        cmd.Parameters.Clear()
    End Sub
End Class

0 个答案:

没有答案