繁体   English   中英

通过vb.net更新SQL Server数据库中的记录

[英]UPDATE Records in a SQL Server Database through vb.net

嗨,我需要您的帮助

我正在努力从vb.net更新数据库sql服务器中的任何记录

第一。 我在vb中创建了一个类,以将所有功能以及按钮UPDATE事件中的所有功能都放进去,即要更有条理。

我已经设法完美地完成了所有编码(更新功能),没有错误,但是令人惊讶的是,它没有更新任何字段。

请帮忙

这是我的课堂,在这里我可以进行所有功能,并从按钮evens调用它们:

 Public Function UpdateDataRecord(Command As String) As Integer
    Try
        SQLConnector.Open()
        SQLCommand = New SqlCommand(Command, SQLConnector)


        Dim ChangeCount As Integer = SQLCommand.ExecuteNonQuery()

        SQLConnector.Close()

        Return ChangeCount
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

    Return 0
End Function

在这里我的更新按钮

 Private Sub updateBtn_Click(sender As Object, e As EventArgs) Handles updateBtn.Click

    If IDTextBox.Text <> "" Then
        If (NameTextBox.Text.Length) >= 3 Then

            Dim UpdateThisNow As String = "Update tblActivity " &
                           "Set Name='" & NameTextBox.Text & "' " &
                         "WHERE ID ='" & IDTextBox.Text & "' "


            If sqlcontrol.UpdateDataRecord(UpdateThisNow) = 0 Then

                MsgBox("Not Found")

            Else
                MsgBox("Successfully updated")

            End If

        Else
            MsgBox("Data Entered too short!")
        End If

    Else
        MsgBox("You must provide ID number")

    End If




End Sub

尝试以此替换您的功能。

Public Function UpdateDataRecord(ByVal name As String, ByVal id As Integer) As Integer
    Dim result As Integer 'will save the affected records count later
    Dim sqlConnStr As String = "ConnectionString" 'put a valid connection string value here
    Dim sqlCmdStr As String = "UPDATE tblActivity SET Name = @Name WHERE ID = @ID" 'your SQL UPDATE query with parameters to avoid SQL injection attacks
    Using sqlConn As New SqlConnection(sqlConnStr) 'declare a SQL connection object and uses your connection string
        Using sqlCmd As New SqlCommand(sqlCmdStr) With {.Connection = sqlConn} 'declare a SQL command object and uses your UPDATE query, and the connection object above
            Try
                sqlConn.Open() 'Open the connection
                With sqlCmd.Parameters
                    .Clear() 'clear the parameters
                    .AddWithValue("Name", name) 'add the value to the parameterized query using the values you got from your textbox
                    .AddWithValue("ID", id)
                End With
                result = sqlCmd.ExecuteNonQuery() 'set the value of the result integer
            Catch ex As Exception
                result = 0
            Finally
                sqlConn.Close()
            End Try
        End Using
    End Using
    Return result
End Function

然后这样称呼它:

sqlcontrol.UpdateDataRecord(NameTextBox.Text, IDTextBox.Text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM