ASP.NET VB.NET - SQL UPDATE命令不起作用

时间:2014-05-19 15:48:32

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

我已经在这个特定的问题上工作了几天,并且搜索SO,MSDN和其他谷歌搜索并没有被证明是有用的。我试图对SQL表进行简单的更新。我的SELECT和INSERT语句都可以正常工作,但由于某种原因,此更新将无法正常工作。我设置了断点并逐步完成,代码似乎工作正常 - 在.ExecuteNonQuery()触发后,Catch ex as Exception永远不会到达。

有谁能让我知道为什么我无法获得SQL更新?

Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
        Dim currentUser = Membership.GetUser(User.Identity.Name)
        Dim username As String = currentUser.UserName
        Dim userId As Guid = currentUser.ProviderUserKey
        UserNameTextBox.Text = username

        ' Get Root Web Config Connection String so you don't have to encrypt it
        Dim rootWebConfig As System.Configuration.Configuration
        rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")
        Dim connString As System.Configuration.ConnectionStringSettings
        connString = rootWebConfig.ConnectionStrings.ConnectionStrings("LocalSqlServer")
        Dim conn As String = connString.ToString
        Dim commandString As String = "UPDATE UserDetails SET FirstName ='" + FirstNameTextBox.Text + "' WHERE UserId ='" + userId.ToString + "'"
        Dim fname As String = FirstNameTextBox.Text

        Dim commandText As String = "UPDATE UserDetails SET FirstName=@firstname WHERE UserId=@UID;"

        Using connection As New SqlConnection(conn)
            Dim command As New SqlCommand(commandText, connection)
            command.CommandType = CommandType.Text


            ' Add UserId parameter for WHERE clause.
            command.Parameters.Add("@UID", SqlDbType.UniqueIdentifier).Value = userId
            ' command.Parameters("@UID").Value = userId
            ' command.Parameters.AddWithValue("@UID", userId)
            ' Use AddWithValue to assign Demographics. 
            command.Parameters.Add("@firstname", SqlDbType.VarChar, 255).Value = fname
            'command.Parameters.AddWithValue("@firstname", fname)
            ' command.Parameters("@firstname").Value = FirstNameTextBox.Text.ToString

            Try
                connection.Open()
                command.ExecuteNonQuery()
                Dim rowsAffected As Integer = command.ExecuteNonQuery()
                Console.WriteLine("RowsAffected: {0}", rowsAffected)

            Catch ex As Exception
                Console.WriteLine(ex.Message)
            Finally
                connection.Close()
            End Try
        End Using
    End Sub 

1 个答案:

答案 0 :(得分:0)

你正在运行" command.ExecuteNonQuery()"两次,这意味着第二次执行可能会返回受影响的0行,因为您已经更新了需要更新的内容,以及您分配给rowsAffected的内容。你确定UPDATE没有发生吗?

编辑:重新评论,你在LoadUser时检查了IsPostBack吗?如果没有,当您点击SaveButton时,您将重新加载现有值,然后您将使用这些现有值进行更新。