Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting using AddWithValue - throws an error?

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.

like image 956
compliance Avatar asked Jul 23 '26 21:07

compliance


2 Answers

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)
like image 88
Tim Schmelter Avatar answered Jul 26 '26 13:07

Tim Schmelter


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)
like image 45
David Avatar answered Jul 26 '26 12:07

David