Inserting data into SQL Server database using VB.N

2019-03-06 01:18发布

I am currently using HDI Membership provider and the design looks as shown below:

enter image description here

Now I am trying to create a new user and insert those values into the database as shown below:

Try
   Dim connectionString As String = "Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
   Using cn As New SqlConnection(connectionString)
      cn.Open()
      Dim cmd As New SqlCommand()
      cmd.CommandText = "INSERT INTO Users VALUES(@Username,@Password,@Email,@PasswordQuestion,@PasswordAnswer)"

      Dim param1 As New SqlParameter()
      param1.ParameterName = "@Username"
      param1.Value = txtUsername.Text.Trim()
      cmd.Parameters.Add(param1)

      Dim param2 As New SqlParameter()
      param2.ParameterName = "@Password"
      param2.Value = txtPassword.Text.Trim()
      cmd.Parameters.Add(param2)

      Dim param3 As New SqlParameter()
      param3.ParameterName = "@Email"
      param3.Value = txtEmail.Text.Trim()
      cmd.Parameters.Add(param3)

      Dim param4 As New SqlParameter()
      param4.ParameterName = "@PasswordQuestion"
      param4.Value = txtSecurityQuestion.Text.Trim()
      cmd.Parameters.Add(param4)

      Dim param5 As New SqlParameter()
      param5.ParameterName = "@PasswordAnswer"
      param5.Value = txtSecurityAnswer.Text.Trim()
      cmd.Parameters.Add(param5)

      cmd.Connection = cn
      cmd.ExecuteNonQuery()
      cn.Close()
   End Using
   Successlbl.show
   Successlbl.show.Text = "Regisration Success."
Catch
   Errolbl.Show()
   Errolbl.Text = "Your account was not created.Please try again."
End Try

Now the problem is the data is not inserting to the database. I would like to know If anyone can point me where I'm going wrong?

1条回答
萌系小妹纸
2楼-- · 2019-03-06 01:40

Your insert statement is incorrect - since you are not specifying any field names you should be supplying values for all columns.

The fix is to supply the names of the columns you are insert into.

The screenshot also shows that there is a required ApplicationName column, so unless it has a DEFAULT defined, you will need to supply that as well.

Assuming you have a DEFAULT defined on ApplicationName:

cmd.CommandText = "INSERT INTO Users ( Username, Password, Email, PasswordQuestion, PasswordAnswer) VALUES(@Username,@Password,@Email,@PasswordQuestion,@PasswordAnswer)"
查看更多
登录 后发表回答