Hi. the first code snippet inserts textbox values into database and it works well:
Public Sub InsertintoTable(ByVal username As String, ByVal password As String)
Dim adp As New SqlCommand("INSERT INTO [users_tbl] (usr_username,usr_password) values ('" & username & "','" & password & "')", con)
adp.ExecuteNonQuery()
End Sub
Instead, I would like to use AddWithValue, so i try this:
Public Sub InsertintoTable(ByVal username As String, ByVal password As String)
Using adp As New SqlCommand("INSERT INTO [users_tbl] (usr_username, usr_password) values (@username, @password)", con)
adp.Parameters.AddWithValue("@usr_username", username)
adp.Parameters.AddWithValue("@usr_password", password)
adp.ExecuteNonQuery()
End Using
End Sub
but unfortunately it throws an Error:
Exception Details: System.Data.SqlClient.SqlException: Must declare the scalar variable "@username".
Why the error? might my AddWithValue snippet be wrong?
Thank you.
The parameter names are different, this works:
adp.Parameters.AddWithValue("@username", username)
adp.Parameters.AddWithValue("@password", password)
or change the sql from
INSERT INTO [users_tbl] (usr_username, usr_password) values (@username, @password)
to
INSERT INTO [users_tbl] (usr_username, usr_password) values (@usr_username, @usr_password)
Your query is expecting these two variables:
@username, @password
But you pass it variables of a different name:
adp.Parameters.AddWithValue("@usr_username", username)
adp.Parameters.AddWithValue("@usr_password", password)
The parameter names need to match. Something like this:
adp.Parameters.AddWithValue("@username", username)
adp.Parameters.AddWithValue("@password", password)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With