Reputation: 434
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.
Upvotes: 2
Views: 1786
Reputation: 460238
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)
Upvotes: 5
Reputation: 219016
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)
Upvotes: 4