嗨。第一代碼片段插入文本框的值到數據庫和它工作得很好:使用AddWithValue插入 - 引發錯誤?
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
代碼段錯了?
謝謝。
未使用的方法我自己,但看起來像你應該有'AddWithV alue(「@ username」,username)''而不是'「@user_username」' – freefaller 2013-03-07 14:19:16
謝謝你是對的。無論如何,我不知道爲什麼AddWithValue有很多參數,這使事情變得複雜。 – compliance 2013-03-07 19:08:52