Home >Database >Mysql Tutorial >How to Fix the 'Parameterized Query Expects Parameter Which Was Not Supplied' Error?

How to Fix the 'Parameterized Query Expects Parameter Which Was Not Supplied' Error?

Linda Hamilton
Linda HamiltonOriginal
2024-12-30 00:13:52948browse

How to Fix the

Troubleshooting "Parameterized Query Expects Parameter Which Was Not Supplied" Error

When executing a parameterized query in your code, you encountered an error indicating that a parameter was not supplied. To resolve this issue, let's examine the code and apply a fix.

In the provided code snippet, a parameterized query is being used to retrieve records from a database based on a search parameter from TextBox2. However, the error message suggests that the '@Parameter1' parameter is not being supplied. To fix this, we need to explicitly add and assign values to the parameters in the 'Parameters' collection of the command object.

The following code modification will address this:

Dim cmd As New SqlCommand
cmd.CommandText = "SELECT * FROM borrow WHERE Department LIKE '%' + @Department + '%'"
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("@Department", SqlDbType.VarChar)

If Not TextBox2.Text Is Nothing Then
    cmd.Parameters("@Department").Value = TextBox2.Text
Else
    cmd.Parameters("@Department").Value = DBNull.Value
End If

con.Open()

In this modified code, we:

  • Add a parameter with the name "@Department" to the command.
  • Check whether the text in TextBox2 is not null (to handle empty search input).
  • If the text is not null, assign the value from TextBox2 to the parameter; otherwise, assign DBNull.Value to handle null input.

The DBNull.Value is used to represent null values in database operations. By adding this check, we ensure that the query will execute correctly even if the search input is empty or null.

The above is the detailed content of How to Fix the 'Parameterized Query Expects Parameter Which Was Not Supplied' Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn