使用AddWithValue插入 - 引发错误?

时间:2013-03-07 14:17:33

标签: asp.net sql sql-server database vb.net

您好。第一个代码片段将文本框值插入数据库,效果很好:

    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



相反,我想使用AddWithValue,所以我试试这个:

    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

但不幸的是它会引发错误:

Exception Details: System.Data.SqlClient.SqlException: Must declare the scalar variable "@username".

为什么会出错?我的AddWithValue代码段可能错了吗?

谢谢。

2 个答案:

答案 0 :(得分:5)

参数名称不同,这有效:

adp.Parameters.AddWithValue("@username", username)
adp.Parameters.AddWithValue("@password", password)

或从

更改sql
INSERT INTO [users_tbl] (usr_username, usr_password) values (@username, @password)

INSERT INTO [users_tbl] (usr_username, usr_password) values (@usr_username, @usr_password)

答案 1 :(得分:4)

您的查询期待这两个变量:

@username, @password

但是你传递了一个不同名称的变量:

adp.Parameters.AddWithValue("@usr_username", username)
adp.Parameters.AddWithValue("@usr_password", password)

参数名称需要匹配。像这样:

adp.Parameters.AddWithValue("@username", username)
adp.Parameters.AddWithValue("@password", password)