How could I pass parameter to sqldataadapter?

只谈情不闲聊 提交于 2021-01-28 14:17:24

问题


I have tried to pass parameter a value, but what it returns is nothing. If I use a simple sql command without parameter I can retrieve all the data from my database. Here is my code:

Public Shared Function RetrieveData() As DataTable
    Connection.Open()
    Try
        sql = "SELECT DEP_ID AS CODE, DEP_NAME AS DEPARTMENT FROM DEPART_TBL WHERE " & FieldName & " LIKE N'%@criteria%'"
        da = New SqlDataAdapter
        da.SelectCommand = New SqlCommand(sql, Connection.SQLConnection)
        da.SelectCommand.Parameters.Add("@criteria", SqlDbType.NChar)
        da.SelectCommand.Parameters("@criteria").Value = "KCL"
        'da.SelectCommand.Parameters.Add("@criteria", SqlDbType.NChar, 10, "DEP_ID")
        'Message.ShowInfo(da.SelectCommand.CommandText.ToString)
        'Exit Function
        dt = New DataTable
        da.Fill(dt)
    Catch ex As Exception
        Message.ShowError(ex.Message)
    End Try
    da.Dispose()
    Connection.Close()
    Return dt
End Function

回答1:


You are searching the string @criteria, you want to use the parameter, so use:

sql = "SELECT DEP_ID AS CODE, DEP_NAME AS DEPARTMENT FROM DEPART_TBL WHERE " & FieldName & " LIKE N'%' + @criteria + '%'"

or you can use it in the parameter:

da.SelectCommand.Parameters("@criteria").Value = "%KCL%"


来源:https://stackoverflow.com/questions/46441899/how-could-i-pass-parameter-to-sqldataadapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!